How to check if PowerShell result contains these words

127 Views Asked by At

I'm doing an IF statement in PowerShell and at some point I do this:

(Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype

which gives me the results in this format, on top of each other

enter image description here

I want to write my IF statement to check whether the output of the command above contains both "TpmPin" and "RecoveryPassword" but not sure what the correct syntax is.

I tried something like this but it doesn't work as expected, the result is always true even if it should be false.

if ((Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype -contains "tpmpin" && "RecoveryPassword")

this doesn't work either:

if ((Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype -contains "tpmpinRecoveryPassword")

p.s I don't want to do nested IF statements because I'm already doing multiple of them.

2

There are 2 best solutions below

3
Mathias R. Jessen On BEST ANSWER

Make the call to Get-BitLockerVolume before the if statement, store the result in a variable, then use the -and operator to ensure both are found:

$KeyProtectors = Get-BitlockerVolume -MountPoint "C:" |ForEach-Object KeyProtector
if($KeyProtectors.KeyProtectorType -contains 'TpmPin' -and $KeyProtectors.KeyProtectorType -contains 'RecoveryPassword'){
    # ... both types were present
}

If you have an arbitrary number of values you want to test the presence of, another way to approach this is to test that none of them are absent:

$KeyProtectors = Get-BitlockerVolume -MountPoint "C:" |ForEach-Object KeyProtector

$mustBePresent = @('TpmPin', 'RecoveryPassword')

if($mustBePresent.Where({$KeyProtectors.KeyProtectorType -notcontains $_}, 'First').Count -eq 0){
    # ... all types were present
}
2
Venkataraman R On

you can write a powershell if check like given below:

if((((Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype) -join ",")  -eq "Tpm,RecoveryPassword") 
{ 
      write-host "matches" 
} 
else 
{
      write-host "does not match"
}

matches

Caveat: As told by @MathiasR.Jessen, this solution assumes the order of the values. So, if the values order changes, above solution will not work. We need to follow the solution provided by @MathiasR.Jessen