I wanted to know what would be the best practice and quickest way to validate a boolean array in PowerShell to see if it's all true respectively all false.
My own approach looks like this:
$boolArray = new-object bool[] 5
0..($boolArray.Length - 1) | ForEach-Object { $boolArray[$_] = $true }
#$boolArray[2] = $false
$boolArray
if (!($boolArray -contains $false)) {
'All is true.'
}
else {
'Contains at least one false.'
}
I'm using -contains to validate the array, but no clue if this is really the best way.
I also wanted to know if -contains stops at the first occurrence or always validates the entire array.
-containsand-inare the Powershell idiomatic way of doing this just as what you have right now is perfectly fine. Both operators will stop at first occurrence: "These operators stop comparing as soon as they detect the first match..." from learn.microsoft.com/en-us/powershell/module/…!($boolArray -contains $false)is the same as$boolArray -notcontains $falseand!($false -in $boolArray)is the same as$false -notin $boolArray.if(-not ($boolArray -ne $true)) { ... }, see duplicate: If all values in 'foreach' are true.