[edit] Performing Windows PowerShell Comparisons
When using the Windows PowerShell comparison operators, it is important to keep in mind that PowerShell will look at the left hand operand of the expression to decide the value type to be used as the basis of the comparison. Having made this decision, if the right hand operand is of a different type PowerShell will attempt to convert it. This concept is probably best described using some examples.
In the following example, both operands are of the same type, so no conversion is performed:
PS C:\Users\Administrator> 10 -eq 20
False
If, however, the operands are of different types a conversion of the right hand operand will be necessary. In the following example, the right hand operand will be converted to a number before the comparison is performed:
PS C:\Users\Administrator> 10 -eq "10"
True
Both case sensitive and case insensitive comparison operators are available when comparing strings and characters. For example, the following commands both perform a case insensitive comparison:
PS C:\Users\Administrator> "hello" -eq "HELLO"
True
PS C:\Users\Administrator> "hello" -ieq "HELLO"
True
Conversely, the following command performs a case sensitive comparison of the same two strings:
PS C:\Users\Administrator> "hello" -ceq "HELLO"
False
[edit] Using Comparison Operators with Arrays and Collections
The Windows PowerShell comparison operators can be used with both arrays and collections. In the case of the basic comparison operators, PowerShell will return all elements which contain the value specified in the right hand operand. For example:
PS C:\Users\Administrator> $myarray = "red, "yellow", "blue", "yellow"
PS C:\Users\Administrator> $myarray -eq "yellow"
yellow
yellow
[edit] Using PowerShell Containment Operators
Alternatively, the containment operators may be used to obtain a true or false result depending on whether a collection or array contains a specified value. The following command returns a value of True because an array element does, indeed, contain the value "red":
PS C:\Users\Administrator> $myarray = "red, "yellow", "blue", "yellow"
PS C:\Users\Administrator> $myarray -contains "red"
True
|
|
Purchase and download the full PDF version of this PowerShell eBook for only $8.99 |
|