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 behaviour 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
PS> 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 avoid this problem, 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' } 

In this case, the array is not expanded, null is compared with the entire array. The result will be false, the array variable is set.

..................Content has been hidden....................

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