PowerShell Operators
Operators combine values. PowerShell's arithmetic operators look like other languages', but its comparison and logical operators are words with a dash (-eq, -and), because <, > and | already mean redirection and piping in a shell. This lesson covers arithmetic, assignment, logical and a few special operators; the next lesson is all about comparisons.
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
add (or concatenate) | 5 + 2 |
7 |
- |
subtract | 5 - 2 |
3 |
* |
multiply (or repeat) | 5 * 2 |
10 |
/ |
divide | 5 / 2 |
2.5 |
% |
remainder | 5 % 2 |
1 |
$price = 19.99
$quantity = 3
$total = $price * $quantity
$total
[math]::Round($total, 1)
[math]::Floor(17 / 5)
17 % 5
[math]::Pow(2, 10)
2 -shl 3 # bit shift left: 2 * 2^359.97
60
3
2
1024
16
For integer division, use [math]::Floor() (or [math]::Truncate() for negative numbers rounding toward zero).
Assignment operators
$score = 10
$score += 5; "after += 5: $score"
$score -= 3; "after -= 3: $score"
$score *= 2; "after *= 2: $score"
$score /= 4; "after /= 4: $score"
$score %= 4; "after %= 4: $score"
$score++; "after ++: $score"
$score--; "after --: $score"
$tags = @('red')
$tags += 'blue'
$tags -join ', 'after += 5: 15
after -= 3: 12
after *= 2: 24
after /= 4: 6
after %= 4: 2
after ++: 3
after --: 2
red, blue
+= also works on strings and arrays. (On arrays it actually builds a new, longer array each time; for big loops see the Arrays lesson.)
Logical operators
| Operator | True when |
|---|---|
-and |
both sides are true |
-or |
at least one side is true |
-xor |
exactly one side is true |
-not or ! |
the operand is false |
$age = 25
$hasTicket = $true
$age -ge 18 -and $hasTicket
$age -lt 18 -or $hasTicket
-not $hasTicket
!($age -gt 30)
$true -xor $trueTrue
True
False
True
False
-and and -or short-circuit: the right side isn't evaluated when the left side already decides the answer. That makes checks like $user -and $user.IsActive safe when $user is $null.
PowerShell 7 operators
PowerShell 7 added several operators known from C# and Bash. They do not work in Windows PowerShell 5.1.
$stock = 0
$stock -gt 0 ? 'in stock' : 'sold out' # ternary
$nickname = $null
$nickname ?? 'anonymous' # null-coalescing
$nickname ??= 'guest' # assign only if null
$nickname
$order = $null
"Status: [$(${order}?.Status)]" # null-conditional member accesssold out
anonymous
guest
Status: []
The variable name must be wrapped in braces for ?. (${order}?.Status), because ? is a valid character in variable names.
The pipeline chain operators && and || run the next command only if the previous one succeeded (&&) or failed (||):
Write-Output 'step 1' && Write-Output 'step 2'
Get-Item ./missing.txt 2>$null || Write-Output 'fallback: file not found'step 1
step 2
fallback: file not found
Special operators
| Operator | Name | Example |
|---|---|---|
.. |
range | 1..5, 'a'..'e' |
, |
array | 1, 2, 3 or ,'single' |
-f |
format | '{0:N2}' -f 3.14159 |
-join, -split |
join / split | 'a,b' -split ',' |
$( ) |
subexpression | "Sum: $(1 + 2)" |
@( ) |
array subexpression | always returns an array |
& |
call | & $scriptBlock, & 'my tool.exe' |
. |
dot-source | . ./helpers.ps1 |
[type] |
cast | [int]'5' |
1..5 -join ' '
'a'..'e' -join ''
5..1 -join ' '
(@(Get-ChildItem ./does-not-exist* )).Count1 2 3 4 5
abcde
5 4 3 2 1
0
@( ) guarantees an array even when a command returns nothing or a single item, so .Count is always reliable.
Test yourself
Why does PowerShell use -gt instead of > for 'greater than'?
- To be different from C#
- Because
>is the output redirection operator in shells >is reserved for classes- There is no reason
What does $null ?? 'default' return in PowerShell 7?
- $null
- 'default'
- An error
- $true
What is 5..1 -join ','?
- 1,2,3,4,5
- 5,4,3,2,1
- 5,1
- An error