Comparison operators and arrays

When comparison operators are used with scalar values (a single item as opposed to an array), the comparison will result in true or false.

When used with an array or collection, the result of the comparison is all matching elements, for example:

1, $null -ne $null                  # Returns 1 
1, 2, 3, 4 -ge 3                    # Returns 3, 4 
'one', 'two', 'three' -like '*e*'   # Returns one and three 

This behavior may be problematic if a comparison is used to test whether or not a variable holding an array exists. In the following example, -eq is used to test that a value has been assigned to a variable called array:

$array = 1, 2 
if ($array -eq $null) { Write-Host 'Variable not set' } 

This test is apparently valid as long as the array does not hold two or more null values. When two or more values are present, the condition unexpectedly returns true:

PS> $array = 1, 2, $null, $null
if ($array -eq $null) { Write-Host 'No values in array' }

No values in array

This happens because the result of the comparison is an array with two null values. If it were a single null value, PowerShell would flatten the array. With two values, it cannot:

[Boolean]@($null)            # Returns false 
[Boolean]@($null, $null)     # Returns true 

To counteract this behavior, when testing whether or not an array exists in a variable, null must be on the left-hand side of the expression. For example, the following Write-Host statement will not execute:

$array = 1, 2, $null, $null 
if ($null -eq $array) { Write-Host 'Variable not set' } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.190