Basic Windows PowerShell 1.0 Operators

Revision as of 15:53, 26 November 2008 by Neil (Talk | contribs) (Windows PowerShell Comparison Operators)

Revision as of 15:53, 26 November 2008 by Neil (Talk | contribs) (Windows PowerShell Comparison Operators)

In Understanding and Creating Windows PowerShell 1.0 Variables we looked at using variables in Windows PowerShell and also described the different types. Being able to create variables is only part of the story however. The next step is to learn how to use these variables in PowerShell commands and scripts. The primary method for working with the data stored in variables is in the form of expressions. In this chapter we will look in detail at PowerShell expressions and operators.

What is an Expression?

The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression:

$theResult = 1 + 2

In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable named $theResult. The operands could just have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example.

In the remainder of this chapter we will look at the various types of operators available in Windows PowerShell.

Windows PowerShell Basic Assignment Operator

We have already looked at briefly the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator:

$x = 10;  // Assigns the value 10 to a variable named x

$x = $y + $z; // Assigns the result of variable y added to variable z to variable x;

$x = $y;   // Assigns the value of variable y to variable x

The assignment operator may also be used to perform a cross-assignment, whereby the values of two variables are swapped:

$x,$y = $y,$x

Using a similar technique, multiple values may be assigned to multiple variables in a single line:

$x,$y,$z = 10,20,30

In addition, assignment operators may be chained together to assign the same value to multiple variables. For example, the following command assigns the value 10 to the variables $x, $y and $z:

$x = $y = $z = 10

Windows PowerShell Compound Assignment Operators

In addition to the basic assignment operator, Windows PowerShell also provides a collection of compound assignment operators which combine an arithmetic operation with the assignment. These operators are outlined in the following table:

OperatorDescriptionExample
+=Add right hand operand to value of variable and place result in variable.$x += 10
-=Subtract right hand operand from value of variable and place result in variable.$x -= 10
*=Multiply value of variable by right hand operand and place result in variable.$x *= 10
x /= yDivide value of variable by right hand operand and place result in variable.$x /= 10
x %= yDivide value of variable by right hand operand and place the remainder in variable.$x % 10

Windows PowerShell Arithmetic Operators

Windows PowerShell provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts the the subtraction operator (-) which takes two operands (i.e one value to be subtracted from another). The behavior of a number of these operators varies depending on whether the operands are numbers, strings, arrays or hashtables.

The following table lists the primary Windows PowerShell arithmetic operators:

OperatorDescriptionExample
-(unary)Negates the value of a variable or expression-10
*Multiplies two values.10 * 20
/Divides two values20 / 10
+Add two values10 + 20
-Subtracts two values2 - 10
%Return the remainder of the division of two values10 % 3

Note that multiple operators may be used in a single expression. For example:

$x = $y * 10 + $z - 5 / 4;

The Addition Operator

If the left hand operand of an addition expression is a number, PowerShell will attempt to convert the right hand operand to a number (if it is not already one) and perform an arithmetic addition. If the right hand operand cannot be converted to a number, an error will be reported:

PS C:\Users\Administrator> $x = 10 + 20    # Both operands are numeric, no conversion required
PS C:\Users\Administrator> $x
30

PS C:\Users\Administrator> $x = 10 + "20"  # Right hand operand is a string, converted to numeric type
PS C:\Users\Administrator> $x
30

PS C:\Users\Administrator> $x = 10 + "twenty"  # Right hand operand is a string, conversion impossible

Cannot convert value "twenty" to type "System.Int32". Error: "Input string was not in a correct for
mat."
At line:1 char:10
+ $x = 10 +  <<<< "twenty"

If both operands are strings, the addition operand concatenates the strings together:

PS C:\Users\Administrator> $string = "Hello, " + "there"
PS C:\Users\Administrator> $string
Hello, there

Similarly, if the operands are arrays or hashtables, the right hand operand will be appended to the end of the left hand operand.

Multiplication Operator

If the left hand operand of a muliplication expression is a number, PowerShell will attempt to convert the right hand operand to a number (if it is not already one) and perform an arithmetic addition. If the right hand operand cannot be converted to a number, an error will be reported:

PS C:\Users\Administrator> $x = 10 * 20   # Both operands are numeric, no conversion required
PS C:\Users\Administrator> $x
200

PS C:\Users\Administrator> $x = 10 * "20"  # Right hand operand is a string, converted to numeric type
PS C:\Users\Administrator> $x
200

PS C:\Users\Administrator> $x = 10 * "twenty"  # Right hand operand is a string, conversion impossible

Cannot convert value "twenty" to type "System.Int32". Error: "Input string was not in a correct for
mat."
At line:1 char:10
+ $x = 10 *  <<<< "twenty"

If the left hand operand is a string and the right hand operand a number, the string will be duplicated the specified number of times:

PS C:\Users\Administrator> $string = "Hello, " * 3
PS C:\Users\Administrator> $string
Hello, Hello, Hello,

Similarly, multiplication of an array causes duplication of array elements as illustrating in the following example:

PS C:\Users\Administrator> $myarray = "red","green","blue"
PS C:\Users\Administrator> $myarray
red
green
blue
PS C:\Users\Administrator> $myarray = $myarray * 3
PS C:\Users\Administrator> $myarray
red
green
blue
red
green
blue
red
green
blue

Division, Subtraction and Modulus Operators

Unlike the above operators, the Windows PowerShell divide, subtract and modulus operators are designed only to work with number. It is not, therefore, possible to divide one string by another or subtract two arrays. In terms of performing conversions, as long as one operand is a number, PowerShell will attempt convert the remaining operand to a number (assuming, of course, that it is not already a number). For example, the following expressions all produce the same result:

PS C:\Users\Administrator> 10 / 20
0.5
PS C:\Users\Administrator> "10" / 20
0.5
PS C:\Users\Administrator> 10 / "20"
0.5

Two operands of type string, however, will not be converted to numbers, instead producing an error message:

PS C:\Users\Administrator> "10" / "20"
Method invocation failed because [System.String] doesn't contain a method named 'op_Division'.
At line:1 char:7
+ "10" /  <<<< "20"=

Windows PowerShell & Operator

The Windows PowerShell & operator is a little know, yet extremely useful operator. Quite simply, it allows a string to be treated as a command. This is particularly useful when creating dynmaic commands within a PowerShell script. In the following example, the following commands assign the string Get-ChildItem to a variable named $mycommand:

PS C:\Users\Administrator> $mycommand="get-childitem"

Simply referencing the string does nothing more than display the value of the variable:

PS C:\Users\Administrator> $mycommand
get-childitem
<pre>

Prefixing the string with the & operator, however, instructs PowerShell that the variable contains a command which is to executed:

<pre>
PS C:\Users\Administrator> &$mycommand


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Users\Administrator


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d-r--         11/7/2008   4:26 PM            Contacts
d-r--         11/7/2008   4:26 PM            Desktop
d-r--         11/7/2008   4:26 PM            Documents
d-r--         11/7/2008   4:26 PM            Downloads

Windows PowerShell Comparison Operators

Windows PowerShell provides a range of comparison operators which can be used to compare one value with another. These operators work both with string and number based values assuming that you are comparing like with like (it is not meaningful, for example, to compare a string with numerical value). In terms of working with strings and characters, both case-sensitive and insensitive operators are supported.

OperatorDescription
-eqEqual to (case insensitive)
-ieqEqual to (case insensitive)
-ceqEqual to (case sensitive)
-neNot equal to (case insensitive)
-ineNot equal to (case insensitive)
-cneNot equal to (case sensitive)
-gtGreater than (case insensitive)
-igtGreater than (case insensitive)
-cgtGreater than (case sensitive)
-geGreater than or equal to (case insensitive)
-igeGreater than or equal to (case insensitive)
-cgeGreater than or equal to (case sensitive)
-ltLess than (case insensitive)
-iltLess than (case insensitive)
-cltLess than (case sensitive)
-leLess than or equal to (case insensitive)
-ileLess than or equal to (case insensitive)
-cleLess than or equal to (case sensitive)
-containsGroup of values in left hand operand contains value specified in right hand operand (case insensitive)
-icontainsGroup of values in left hand operand contains value specified in right hand operand (case insensitive)
-ccontainsGroup of values in left hand operand contains value specified in right hand operand (case sensitive)
-notcontainsGroup of values in left hand operand does not contain value specified in right hand operand (case insensitive)
-inotcontainsGroup of values in left hand operand does not contain value specified in right hand operand (case insensitive)
-cnotcontainsGroup of values in left hand operand does not contain value specified in right hand operand (case sensitive)

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 folloing command performs a case sensitive comparison of the same two string:

PS C:\Users\Administrator> "hello" -ceq "HELLO"
False

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

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":

PS C:\Users\Administrator> $myarray = "red, "yellow", "blue", "yellow"
PS C:\Users\Administrator> $myarray -contains "red"
True