Changes

Basic Windows PowerShell 1.0 Operators

2,238 bytes added, 15:53, 26 November 2008
Windows PowerShell Comparison Operators
<tr>
</table>
 
== 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:
 
<pre>
PS C:\Users\Administrator> 10 -eq 20
False
</pre>
 
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:
 
<pre>
PS C:\Users\Administrator> 10 -eq "10"
True
</pre>
 
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:
 
<pre>
PS C:\Users\Administrator> "hello" -eq "HELLO"
True
PS C:\Users\Administrator> "hello" -ieq "HELLO"
True
</pre>
 
Conversely, the folloing command performs a case sensitive comparison of the same two string:
 
<pre>
PS C:\Users\Administrator> "hello" -ceq "HELLO"
False
</pre>
 
== 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:
 
<pre>
PS C:\Users\Administrator> $myarray = "red, "yellow", "blue", "yellow"
PS C:\Users\Administrator> $myarray -eq "yellow"
yellow
yellow
</pre>
 
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 comamnd returns a value of ''True'' because an array element does, indeed, contain the value "red":
 
<pre>
PS C:\Users\Administrator> $myarray = "red, "yellow", "blue", "yellow"
PS C:\Users\Administrator> $myarray -contains "red"
True
</pre>