Home > Blockchain >  How to check if PowerShell result contains these words
How to check if PowerShell result contains these words

Time:11-01

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.

CodePudding user response:

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
}

CodePudding user response:

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

  • Related