Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if PowerShell result contains these words

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading