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.
-contains
and -in
are the PowerShell idiomatic way of doing this type of linear comparison, just as what you have right now is perfectly fine and most likely the most efficient way of doing it linearly. Additionally, both operators will stop at first occurrence, see Containment operators:
These operators stop comparing as soon as they detect the first match...
Another notable mention is that these operators have their negated counterparts, meaning, these comparisons equate:
!($boolArray -contains $false)
same as $boolArray -notcontains $false
!($false -in $boolArray)
same as $false -notin $boolArray
For collections of bigger size, you may opt for a hash-based lookup, the types you may often see being used for this type of comparison are HashSet<T>
and IDictionary
implementing types, such as Hash tables.