Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

Simple Operators

Once you have defined your data, the next step is to work with it.

Arithmetic Operators

The arithmetic operators let you perform mathematical operations on your data, as shown in Table A-5.

Note

The System.Math class in the .NET Framework offers many powerful operations in addition to the native operators supported by PowerShell:

PS > [Math]::Pow([Math]::E, [Math]::Pi)
23.1406926327793

See “Working with the .NET Framework” to learn more about using PowerShell to interact with the .NET Framework.

Table A-5. PowerShell arithmetic operators
Operator Meaning

+

The addition operator:

$leftValue + $rightValue

When used with numbers, returns their sum.

When used with strings, returns a new string created by appending the second string to the first.

When used with arrays, returns a new array created by appending the second array to the first.

When used with hashtables, returns a new hashtable created by merging the two hashtables. Since hashtable keys must be unique, PowerShell returns an error if the second hashtable includes any keys already defined in the first hashtable.

When used with any other type, PowerShell uses that type’s addition operator (op_Addition) if it implements one.

-

The subtraction operator:

$leftValue - $rightValue

When used with numbers, returns their difference.

This operator does not apply to strings, arrays, or hashtables.

When used with any other type, PowerShell uses that type’s subtraction operator (op_Subtraction) if it implements one.

*

The multiplication operator:

$leftValue * $rightValue

When used with numbers, returns their product.

When used with strings ("=" * 80), returns a new string created by appending the string to itself the number of times you specify.

When used with arrays (1..3 * 7), returns a new array created by appending the array to itself the number of times you specify.

This operator does not apply to hashtables.

When used with any other type, PowerShell uses that type’s multiplication operator (op_Multiply) if it implements one.

/

The division operator:

$leftValue / $rightValue

When used with numbers, returns their quotient.

This operator does not apply to strings, arrays, or hashtables.

When used with any other type, PowerShell uses that type’s division operator (op_Division) if it implements one.

%

The modulus operator:

$leftValue % $rightValue

When used with numbers, returns the remainder of their division.

This operator does not apply to strings, arrays, or hashtables.

When used with any other type, PowerShell uses that type’s modulus operator (op_Modulus) if it implements one.

+=

-=

*=

/=

%=

Assignment operators:

$variable operator= value

These operators match the simple arithmetic operators (+, -, *, /, and %) but store the result in the variable on the lefthand side of the operator. It is a short form for

$variable = $variable operator value.

Logical Operators

The logical operators let you compare Boolean values, as shown in Table A-6.

Table A-6. PowerShell logical operators
Operator Meaning

-and

Logical AND:

$leftValue -and $rightValue

Returns $true if both lefthand and righthand arguments evaluate to $true. Returns $false otherwise.

You can combine several -and operators in the same expression:

$value1 -and $value2 -and $value3 …

PowerShell implements the -and operator as a short-circuit operator and evaluates arguments only if all arguments preceding it evaluate to $true.

-or

Logical OR:

$leftValue -or $rightValue

Returns $true if the lefthand or righthand arguments evaluate to $true. Returns $false otherwise.

You can combine several -or operators in the same expression:

$value1 -or $value2 -or $value3 ...

PowerShell implements the -or operator as a short-circuit operator and evaluates arguments only if all arguments preceding it evaluate to $false.

-xor

Logical exclusive OR:

$leftValue -xor $rightValue

Returns $true if either the lefthand or righthand argument evaluates to $true, but not if both do.

Returns $false otherwise.

-not

!

Logical NOT:

-not $value

Returns $true if its righthand (and only) argument evaluates to $false. Returns $false otherwise.

Binary Operators

The binary operators, listed in Table A-7, let you apply the Boolean logical operators bit by bit to the operator’s arguments. When comparing bits, a 1 represents $true, whereas a 0 represents $false.

Table A-7. PowerShell binary operators
Operator Meaning

-band

Binary AND:

$leftValue -band $rightValue

Returns a number where bits are set to 1 if the bits of the lefthand and righthand arguments at that position are both 1. All other bits are set to 0.

For example:

PS > $int1 = 0b110110110
PS > $int2 = 0b010010010
PS > $result = $int1 -band $int2
PS > [Convert]::ToString($result, 2)
10010010

-bor

Binary OR:

$leftValue -bor $rightValue

Returns a number where bits are set to 1 if either of the bits of the lefthand and righthand arguments at that position is 1. All other bits are set to 0.

For example:

PS > $int1 = 0b110110110
PS > $int2 = 0b010010010
PS > $result = $int1 -bor $int2
PS > [Convert]::ToString($result, 2)
110110110

-bxor

Binary exclusive OR:

$leftValue -bxor $rightValue

Returns a number where bits are set to 1 if either of the bits of the lefthand and righthand arguments at that position is 1, but not if both are. All other bits are set to 0.

For example:

PS > $int1 = 0b110110110
PS > $int2 = 0b010010010
PS > $result = $int1 -bxor $int2
PS > [Convert]::ToString($result, 2)
100100100

-bnot

Binary NOT:

-bnot $value

Returns a number where bits are set to 1 if the bit of the righthand (and only) argument at that position is set to 1. All other bits are set to 0.

For example:

PS > $int1 = 0b110110110
PS > $result = -bnot $int1
PS > [Convert]::ToString($result, 2)
11111111111111111111111001001001

-shl

Binary shift left:

$value -shl $count

Shifts the bits of a number to the left $count places. Bits on the righthand side are set to 0.

For example:

PS > $int1 = 438
PS > [Convert]::ToString($int1, 2)
110110110

PS > $result = $int1 -shl 5
PS > [Convert]::ToString($result, 2)
11011011000000

-shr

Binary shift right:

$value -shr $count

Shifts the bits of a number to the right $count places. For signed values, bits on the lefthand side have their sign preserved.

For example:

PS > $int1 = -2345
PS > [Convert]::ToString($int1, 2)
11111111111111111111011011010111

PS > $result = $int1 -shr 3
PS > [Convert]::ToString($result, 2)
11111111111111111111111011011010

Other Operators

PowerShell supports several other simple operators, as listed in Table A-8.

Table A-8. Other PowerShell operators
Operator Meaning

-replace

The replace operator:

"target" -replace "pattern","replacement"

Returns a new string, where the text in "target" that matches the regular expression "pattern" has been replaced with the replacement text "replacement".

"target" -replace "pattern",{ scriptblock }

Returns a new string, where the text in "target" that matches the regular expression "pattern" has been replaced with the output value of the script block supplied. In the script block, the $_ variable represents the current System.Text.RegularExpressions.Match.

By default, PowerShell performs a case-insensitive comparison. The -ireplace operator makes this case-insensitivity explicit, whereas the -creplace operator performs a case-sensitive comparison.

If the regular expression pattern contains named captures or capture groups, the replacement string may reference those as well.

For example:

PS > "Hello World" -replace "(.*) (.*)",'$2 $1'
World Hello

If "target" represents an array, the -replace operator operates on each element of that array.

For more information on the details of regular expressions, see Appendix B.

-f

The format operator:

"Format String" -f values

Returns a string where the format items in the format string have been replaced with the text equivalent of the values in the value array.

For example:

PS > "{0:n0}" -f 1000000000
1,000,000,000

The format string for the format operator is exactly the format string supported by the .NET String.Format method.

For more details about the syntax of the format string, see Appendix D.

-as

The type conversion operator:

$value -as [Type]

Returns $value cast to the given .NET type. If this conversion is not possible, PowerShell returns $null.

For example:

PS > 3/2 -as [int]
2
PS > $result = "Hello" -as [int]
PS > $result -eq $null
True

-split

The unary split operator:

-split "Input String"

Breaks the given input string into an array, using whitespace (\s+) to identify the boundary between elements. It also trims the results.

For example:

PS > -split "  Hello    World   "
Hello
World

The binary split operator:

"Input String" -split "delimiter",maximum,options
"Input String" -split { Scriptblock },maximum

Breaks the given input string into an array, using the given delimiter or script block to identify the boundary between elements.

Delimiter is interpreted as a regular expression match. Scriptblock is called for each character in the input, and a split is introduced when it returns $true.

Maximum defines the maximum number of elements to be returned, leaving unsplit elements as the last item. This item is optional. Use "0" for unlimited if you want to provide options but not alter the maximum.

Options define special behavior to apply to the splitting behavior. The possible enumeration values are:

  • SimpleMatch: Split on literal strings, rather than regular expressions they may represent.

  • RegexMatch: Split on regular expressions. This option is the default.

  • CultureInvariant: Does not use culture-specific capitalization rules when doing a case-insensitive split.

  • IgnorePatternWhitespace: Ignores spaces and regular expression comments in the split pattern.

  • Multiline: Allows the ^ and $ characters to match line boundaries, not just the beginning and end of the content.

  • Singleline: Treats the ^ and $ characters as the beginning and end of the content. This option is the default.

  • IgnoreCase: Ignores the capitalization of the content when searching for matches.

  • ExplicitCapture: In a regular expression match, only captures named groups. This option has no impact on the -split operator.

For example:

PS > "1a2B3" -split "[a-z]+",0,"IgnoreCase"
1
2
3

-join

The unary join operator:

-join ("item1","item2",...,"item_n")

Combines the supplied items into a single string, using no separator. For example:

PS > -join ("a","b")
ab

The binary join operator:

("item1","item2",...,"item_n") -join Delimiter

Combines the supplied items into a single string, using Delimiter as the separator. For example:

PS > ("a","b") -join ", "
a, b