Comparison, Logical, and Arithmetic Operators
How PowerShell's arithmetic, comparison, logical and type operators really behave, including collection filtering, $null placement and string-versus-number traps.
By The Dark DebuggerUpdated 29 min read
This article covers the operators you use in nearly every PowerShell line: arithmetic,
assignment, comparison, logical and type operators, plus the precedence rules that tie
them together. It assumes you have read Variables and Data Types
and The Object Pipeline. String operators such as -f,
-split and -replace get their own article next, in
String Formatting, Split, Join, Replace, and Other Operators.
A few examples use if and foreach before their own articles. They work the way you
would expect from any language; the details are in
Conditionals and Loops.
Why PowerShell operators look strange
Most languages compare with > and ==. PowerShell cannot, because it is a shell first:
> already means "redirect output to a file". Here is what happens when you forget that
in a disk-space check:
$freeGB = 12
if ($freeGB > 10) { 'Plenty of space' }
Get-ChildItem -Name
Get-Content ./1010
12No error, no "Plenty of space". The condition wrote the value of $freeGB into a new
file called 10, produced no output, and an empty result counts as false. The mirror
image fails loudly at least:
$freeGB = 4
if ($freeGB < 10) { 'Low disk space' }ParserError:
Line |
1 | if ($freeGB < 10) { 'Low disk space' }
| ~
| The '<' operator is reserved for future use.So PowerShell spells its comparison operators as words with a dash: -gt, -lt,
-eq. They look odd for a week and then read naturally.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition (also concatenation) | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication (also repetition) | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
% | Remainder (modulus) | 7 % 2 | 1 |
7 + 2
7 - 2
7 * 2
7 / 2
7 % 29
5
14
3.5
1Division never truncates
If you come from C, Java or Bash arithmetic, 7 / 2 giving 3.5 is the first surprise.
PowerShell keeps an integer only when the division is exact:
10 / 5
(10 / 5).GetType().Name
7 / 2
(7 / 2).GetType().Name2
Int32
3.5
DoubleThe second surprise is how you get an integer back. Casting with [int] rounds, and it
uses banker's rounding: halves go to the nearest even number.
[int](7 / 2)
[int]2.5
[int]3.5
[int]4.54
2
4
4[int]2.5 is 2 and [int]3.5 is 4. If you are splitting 5 servers into batches and
cast 5 / 2 to [int], you get 2 batches, not 3. Pick the function that says what you
mean instead:
[math]::Floor(7 / 2)
[math]::Truncate(-7 / 2)
[math]::Floor(-7 / 2)
[math]::Ceiling(7 / 2)
[math]::Round(2.5)
[math]::Round(2.5, [MidpointRounding]::AwayFromZero)
[math]::Round(3.14159, 2)3
-3
-4
4
2
3
3.14Floorrounds down,Ceilingrounds up,Truncatedrops the fraction (toward zero, which differs fromFloorfor negative numbers).[math]::Roundalso uses banker's rounding by default. PassAwayFromZerofor the school-book rule.- For "how many batches of N do I need",
[math]::Ceiling($total / $batchSize)is the answer.
Remainder keeps the sign of the left operand
% is handy for "every Nth item" and even/odd checks. With a negative left operand the
result is negative, which matters if you use it to wrap an index:
17 % 5
-17 % 52
-2Powers, roots and the rest of [math]
PowerShell has no exponent operator. ** is a syntax error:
2 ** 10ParserError:
Line |
1 | 2 ** 10
| ~
| You must provide a value expression following the '*' operator.Use the .NET [math] class (Pow, Sqrt, Abs, Max, Min, Log10 and friends).
Note that Pow returns a Double:
[math]::Pow(2, 10)
[math]::Pow(2, 10).GetType().Name
[math]::Sqrt(144)1024
Double
12Byte suffixes: KB, MB, GB, TB, PB
Numeric literals accept binary size suffixes, which makes disk and memory maths readable:
1KB
1GB
5GB / 1MB
$bytes = 7730941133
$bytes / 1GB
[math]::Round($bytes / 1GB, 1)1024
1073741824
5120
7.20000000018626
7.2Dividing by 1GB is how you turn a file's Length into gigabytes. Round only when you
display the number, not before you compare it. (Overflow is also handled for you:
[int]::MaxValue + 1 quietly becomes the Double 2147483648 instead of wrapping to a
negative number.)
The left operand decides what + and * mean
Arithmetic operators are polymorphic. PowerShell looks at the left operand's type and converts the right operand to match:
'5' + 3
5 + '3'
'5' * 3
'-' * 20
@(1, 2) + 353
8
555
--------------------
1
2
3A string on the left means concatenation ('5' + 3 is "53") or repetition. A number on
the left means arithmetic, and the string is parsed as a number. An array on the left
means "append". When the conversion is impossible you get an error, not a guess:
5 + 'three'InvalidArgument: Cannot convert value "three" to type "System.Int32". Error: "The input string 'three' was not in a correct format."Remember this rule; it comes back with a vengeance in comparisons.
Increment and decrement
++ and -- add or subtract one from a variable. Used as a statement on its own line,
$retries++ produces no output. Inside an expression the position matters: postfix
returns the old value, prefix the new one:
$i = 5
$a = $i++
"a=$a i=$i"
$b = ++$i
"b=$b i=$i"a=5 i=6
b=7 i=7Assignment operators
| Operator | Same as | Notes |
|---|---|---|
= | Assign | |
+= | $x = $x + y | Also appends to strings and arrays |
-= | $x = $x - y | |
*= | $x = $x * y | |
/= | $x = $x / y | |
%= | $x = $x % y | |
??= | assign only if $x is $null | PowerShell 7 only, see advanced operators |
The numeric forms do what the table says. The interesting one is +=, because it follows
the left-operand rule: on a string it concatenates, building a value up piece by piece:
$log = 'deploy started'
$log += '; build ok'
$log += '; tests ok'
$logdeploy started; build ok; tests okOn an array, += creates a brand new array each time. That is fine for a dozen items and
slow for tens of thousands; Arrays, Hashtables, and Custom Objects
measures it and shows the fix.
Multiple assignment
You can assign several variables at once. The last variable soaks up whatever is left, and the same syntax swaps two values without a temporary variable:
$dbHost, $port = 'db01.internal', 5432
"$dbHost : $port"
$first, $rest = 'web01', 'web02', 'web03', 'web04'
$first
$rest
$a = 'blue'; $b = 'green'
$a, $b = $b, $a
"a=$a b=$b"db01.internal : 5432
web01
web02
web03
web04
a=green b=blueThat blue/green swap is exactly what a blue-green deployment script does when it flips
the live and idle slots.
Comparison operators
| Operator | Meaning | Case-sensitive form | Explicitly insensitive |
|---|---|---|---|
-eq | equal | -ceq | -ieq |
-ne | not equal | -cne | -ine |
-gt | greater than | -cgt | -igt |
-ge | greater than or equal | -cge | -ige |
-lt | less than | -clt | -ilt |
-le | less than or equal | -cle | -ile |
With two numbers they behave exactly as you expect: 10 -ge 10 is True, 3 -le 2 is
False. Everything interesting happens with strings, mixed types and collections.
Case sensitivity: the c and i prefixes
String comparisons ignore case by default. Prefix any comparison operator with c to make
it case-sensitive; the i prefix exists only to make the default explicit:
'Production' -eq 'production'
'Production' -ceq 'production'
'Production' -ieq 'PRODUCTION'True
False
TrueThe default suits Windows, where file names and most identifiers ignore case. Reach for
-ceq when case carries meaning: Linux paths, Git branch names, base64 tokens, passwords.
The left operand sets the type of the comparison
This is the rule that causes more real bugs than any other in this article. As with arithmetic, PowerShell converts the right operand to the type of the left one:
'10' -lt 9
10 -lt '9'
'abc' -gt 5True
False
True'10' -lt 9 compares two strings, character by character, and '1' sorts before '9'.
Swap the sides and you get a numeric comparison. Version numbers fall into the same trap:
'1.10.0' -gt '1.9.0'
[version]'1.10.0' -gt [version]'1.9.0'
[version]'2.0' -eq [version]'2.0.0'False
True
FalseAs strings, 1.10.0 is "less than" 1.9.0. Cast to [version] and the parts are compared as
numbers. (The last line is a quirk of [version]: a missing build number is -1, not 0, so
2.0 and 2.0.0 are different versions. Compare versions with the same number of parts.)
Dates work the same way. When the left side is a DateTime, a string on the right is parsed
as a date:
$cutoff = Get-Date '2026-11-01'
(Get-Date '2026-11-09') -gt $cutoff
(Get-Date '2026-11-09') -gt '2026-12-25'True
FalseData from outside is almost always a string
Import-Csv, Read-Host, environment variables, command-line output and most REST
responses give you strings. Before you compare them as numbers, versions or dates, cast
them: [double]$row.FreeGB, [version]$row.AgentVersion, [datetime]$row.LastPatch.
The Where you'll use this section shows what goes wrong otherwise.
Wildcard matching with -like and -notlike
-like compares a string to a wildcard pattern: * is any run of characters, ? is
exactly one character, and [a-d] is one character from a set or range. The whole string
must match the pattern.
'web-prod-01' -like 'web-prod-*'
'web-prod-01' -like 'web-*-0?'
'db-prod-01' -like '[a-d]b-*'
'WEB-PROD-01' -like 'web-prod-*'
'WEB-PROD-01' -clike 'web-prod-*'
'web-stage-01' -notlike '*-prod-*'True
True
True
True
False
TrueBecause the whole string has to match, a pattern without wildcards is just an equality test:
'report.txt' -like 'report'
'report.txt' -like 'report*'False
TrueSquare brackets are wildcard syntax, so a file name containing them breaks the pattern.
Escape the literal part with [WildcardPattern]::Escape():
$file = 'backup[2026-11].zip'
$file -like 'backup[2026-11].zip'
$file -like [WildcardPattern]::Escape('backup[2026-11].zip')
[WildcardPattern]::Escape('backup[2026-11].zip')WildcardPatternException: The specified wildcard character pattern is not valid: backup[2026-11].zip
True
backup`[2026-11`].zipRegular expressions with -match
-match tests a string against a regular expression. Unlike -like, the pattern can match
anywhere in the string, and when it matches, PowerShell fills the automatic $Matches
hashtable with what was captured:
$line = '2026-11-09 14:02:17 ERROR [payments] Timeout after 30000 ms calling bank-gateway'
$line -match 'ERROR'
$line -match '\[(\w+)\] Timeout after (\d+) ms'
$Matches
$Matches[1]
[int]$Matches[2] / 1000True
True
Name Value
---- -----
2 30000
1 payments
0 [payments] Timeout after 30000 ms
payments
30$Matches[0] is the whole match and $Matches[1], $Matches[2] are the capture groups.
Captures are strings, so the timeout needed [int] before the division. Named groups read
better in real scripts:
$line = '2026-11-09 14:02:17 ERROR [payments] Timeout after 30000 ms calling bank-gateway'
if ($line -match '^(?<date>\S+) (?<time>\S+) (?<level>\w+)') {
"$($Matches.level) at $($Matches.time)"
}ERROR at 14:02:17-notmatch negates, and -cmatch is the case-sensitive version ('ERROR' -cmatch 'error'
is False). Two rules to remember: $Matches is only updated when a match succeeds, and it is not
updated at all when the left side is a collection. In both cases you silently get the
values from an earlier match:
'ERROR disk full' -match 'disk (\w+)'
$Matches[1]
'INFO all good' -match 'disk (\w+)'
$Matches[1]
'ERROR a', 'ERROR b' -match 'ERROR (\w)'
$Matches[1]True
full
False
full
ERROR a
ERROR b
fullSo only read $Matches inside an if that tested a single string. Regular
expressions themselves get a full article in Regular Expressions.
-contains and -in: membership, not substrings
-contains asks "does this collection contain this exact item?". -in asks the same
question with the operands reversed. Both return a single True or False:
$allowed = 'web01', 'web02', 'db01'
$allowed -contains 'db01'
'db01' -in $allowed
'cache01' -notin $allowed
$allowed -notcontains 'cache01'True
True
True
TrueHere is the classic mix-up. -contains sounds like a substring test, and it is not:
$hostname = 'web01.prod.internal'
$hostname -contains 'prod'
$hostname -like '*prod*'
$hostname.Contains('prod')False
True
TrueA single string is treated as a one-item collection, and that item is not equal to
'prod'. For substrings use -like '*prod*', -match 'prod', or the string's own
.Contains() method.
The second mix-up is getting the operands backwards. Neither line below is an error; both are just wrong:
$allowed = 'web01', 'web02', 'db01'
$allowed -in 'db01'
'db01' -contains $allowedFalse
FalseMemory aid: the collection goes on the side the operator "points" from. $list -contains $item, $item -in $list. Both are case-insensitive by default (-ccontains and -cin
are the case-sensitive forms), while the string .Contains() method is case-sensitive:
$allowed -contains 'WEB01' is True, but 'WEB01'.Contains('web') is False.
Comparisons against a collection filter it
When the left operand is a collection, comparison operators do not return True or
False. They return the elements that match:
$statusCodes = 200, 200, 404, 500, 200, 503
$statusCodes -eq 200
$statusCodes -ge 500
$statusCodes -ne 200
($statusCodes -ge 500).Count200
200
200
500
503
404
500
503
2This is a feature: it is a fast filter without Where-Object. It works for -like and
-match too:
$logFiles = 'app.log', 'app.log.1', 'error.log', 'readme.txt'
$logFiles -like '*.log'
$logFiles -match '\.log(\.\d+)?$'app.log
error.log
app.log
app.log.1
error.logThe trap is using a filter where you meant a yes/no question. if then judges the
filtered result, and an array that holds a single 0 is false:
$exitCodes = 0, 1, 0
if ($exitCodes -eq 0) { 'some step succeeded' } else { 'no step succeeded' }
$exitCodes = 1, 0
if ($exitCodes -eq 0) { 'some step succeeded' } else { 'no step succeeded' }
$exitCodes -eq 0some step succeeded
no step succeeded
0The first test "worked" because two zeros came back, and any array with two or more
elements is true. The second returned one zero, which is false, so the script reported the
opposite of the truth. When you want a yes/no answer about a collection, ask with
-contains, or count the filter's result:
$exitCodes = 1, 0
if ($exitCodes -contains 0) { 'some step succeeded' } else { 'no step succeeded' }
if (@($exitCodes -eq 0).Count -gt 0) { 'some step succeeded' }some step succeeded
some step succeededPut $null on the left
The filtering behaviour is why every PowerShell style guide says to write $null -eq $x
rather than $x -eq $null. With a collection on the left, -eq $null filters out the
null elements instead of testing the variable:
$servers = 'web01', $null, 'web02'
$servers -eq $null
($servers -eq $null).Count
$null -eq $servers1
FalseThe first line printed nothing you can see: it returned the one $null element, and
$null displays as nothing. The count confirms it found one. With $null on the left the
question is the one you meant: "is $servers itself null?" It is not.
Here is how that bites in a real check. A query returns an empty array, and you test whether anything came back:
$results = @()
if ($results -eq $null) { 'nothing came back' } else { 'got results' }
if ($null -eq $results) { 'nothing came back' } else { 'got results' }
$results.Countgot results
got results
0Neither form says "nothing came back", because an empty array is not $null. The honest
test for "anything returned?" is $results.Count -eq 0. Now the case where the wrong side
lies to you:
$results = $null, $null
if ($results -ne $null) { 'got results' } else { 'nothing came back' }
if ($null -ne $results) { 'got results' } else { 'nothing came back' }nothing came back
got results$results -ne $null filtered out both nulls, leaving an empty (false) result. $null -ne $results correctly answers "the variable holds something".
$null is not equal to zero or to an empty string. For text, use the [string] helpers:
$null -eq 0
$null -eq ''
'' -eq $null
0 -eq $null
[string]::IsNullOrEmpty('')
[string]::IsNullOrWhiteSpace(' ')False
False
False
False
True
TrueLogical operators
| Operator | Meaning | $true when |
|---|---|---|
-and | logical AND | both sides are true |
-or | logical OR | at least one side is true |
-xor | exclusive OR | exactly one side is true |
-not | logical NOT | the operand is false |
! | same as -not | the operand is false |
A realistic alert rule: page someone when CPU is above 90% or free memory is below 10%, but only outside business hours (during the day the team is watching the dashboard):
$cpu = 91
$memoryFree = 12
$isBusinessHours = $true
($cpu -gt 90 -or $memoryFree -lt 10) -and -not $isBusinessHours
($cpu -gt 90 -or $memoryFree -lt 10) -and $isBusinessHoursFalse
TrueShort-circuit evaluation
-and stops as soon as the left side is false, and -or stops as soon as the left side is
true. The right side never runs:
function Test-Slow { Write-Host ' (Test-Slow ran)'; $true }
'and:'
$false -and (Test-Slow)
'or:'
$true -or (Test-Slow)
'and, left true:'
$true -and (Test-Slow)and:
False
or:
True
and, left true:
(Test-Slow ran)
TrueUse it to guard property access on something that might be missing, and to put cheap checks
before expensive ones (a Test-Path before a network call):
$config = $null
if ($config -and $config.Retries -gt 3) { 'retry heavy' } else { 'default retries' }default retries-and and -or have the same precedence
In C, Python and JavaScript, AND binds tighter than OR. In PowerShell they have equal precedence and are evaluated left to right:
$true -or $true -and $false
$true -or ($true -and $false)False
TrueThe first line is ($true -or $true) -and $false. If you translate a condition from
another language without adding parentheses, you can change its meaning silently.
-not has the opposite problem: it binds tighter than comparisons.
$count = 5
-not $count -eq 3
-not ($count -eq 3)False
True-not $count -eq 3 means (-not 5) -eq 3, which is $false -eq 3, which is false. My
rule: whenever -and, -or or -not meets another operator, add parentheses.
Commands inside conditions need parentheses
Operators only work in expression mode. Write a command name first and PowerShell parses
everything after it as arguments, including -and:
Test-Path /etc -and Test-Path /tmpTest-Path: A parameter cannot be found that matches parameter name 'and'.Wrap each command in parentheses so it runs first and its result becomes the operand:
(Test-Path /etc) -and (Test-Path /tmp)TrueType operators: -is, -isnot, -as
-is tests an object's type; -isnot is the negation:
42 -is [int]
'42' -is [int]
3.5 -is [double]
(Get-Date) -is [datetime]
@(1, 2) -is [array]
42 -isnot [string]
42 -is [ValueType]True
False
True
True
True
True
True-is checks the real type. '42' is a string that looks like a number, so -is [int] is
false. It also understands inheritance: an [int] is a [ValueType].
-as converts if it can and returns $null if it cannot, where a cast throws:
'42' -as [int]
'forty-two' -as [int]
'3.7' -as [int]
'2026-11-09' -as [datetime]
$null -eq ('forty-two' -as [int])42
4
Monday, 09 November 2026 00:00:00
TrueThe second line printed nothing because the result was $null. Notice '3.7' became 4: the
conversion rounds, just like a cast. (The date's display format follows your culture
settings, so yours may look different.) Compare a cast of the same bad input:
[int]'forty-two'InvalidArgument: Cannot convert value "forty-two" to type "System.Int32". Error: "The input string 'forty-two' was not in a correct format."That makes -as ideal for validating input, with one catch. An empty string and $null
convert to 0, not $null:
'' -as [int]
[int]''
$null -as [int]0
0
0So a validator has to treat empty input separately:
$inputs = '8080', 'http', '443', ''
foreach ($value in $inputs) {
$port = $value -as [int]
if ($null -eq $port -or $value -eq '') { "skip '$value': not a port number" }
else { "port $port" }
}port 8080
skip 'http': not a port number
port 443
skip '': not a port numberPowerShell also has bitwise operators (-band, -bor, -bxor, -bnot, -shl,
-shr) for working with flag values; 5 -band 3 is 1 and 1 -shl 4 is 16. You will
rarely need them outside Windows API and permission-mask work.
Operator precedence
When an expression mixes operators, PowerShell applies them in this order (highest first). This is a condensed version of the official about_Operator_Precedence table:
| Level | Operators |
|---|---|
| 1 | Grouping and subexpressions: ( ), $( ), @( ) |
| 2 | Member access ., static member ::, indexing [0] |
| 3 | Casts such as [int] |
| 4 | Unary -split, unary -join |
| 5 | Comma , (builds arrays) |
| 6 | ++, -- |
| 7 | -not, ! |
| 8 | Range .. |
| 9 | Format -f |
| 10 | Unary minus - |
| 11 | *, /, % |
| 12 | +, - |
| 13 | Bitwise operators |
| 14 | All comparison operators, -like, -match, -replace, -contains, -in, -is, -as, binary -split and -join |
| 15 | -and, -or, -xor (equal precedence, left to right) |
| 16 | Pipeline |, redirection, then assignment (=, +=, ...) last |
A few lines that show the table in action:
2 + 3 * 4
(2 + 3) * 4
10 - 2 -gt 7
1..3 + 10
1, 2 + 3
'{0}' -f 1 + 1
[int]'7' + '3'
[string]7 + 314
20
True
1
2
3
10
1
2
3
11
10
73Reading those: arithmetic runs before comparison, so 10 - 2 -gt 7 is 8 -gt 7. The
range and comma bind tighter than +, so 1..3 + 10 appends 10 to the array 1,2,3, and
1, 2 + 3 is (1, 2) + 3, not 1, 5. -f runs before +, so the format produced '1'
and then + 1 concatenated. A cast applies to the value right after it, so [int]'7' + '3'
is numeric and [string]7 + 3 is concatenation.
You do not need to memorise the table. You need to remember that it exists, and to add parentheses whenever you are not sure.
Where you'll use this
Pre-deployment gates are a good example of operators doing real work. Before a release, a script reads an inventory export and decides which servers are safe to deploy to: enough disk, a recent monitoring agent, recent patches. Here is the export:
Server,Role,FreeGB,AgentVersion,LastPatch
web-prod-01,web,48.2,2.14.0,2026-10-28
web-prod-02,web,9.5,2.9.3,2026-10-28
db-prod-01,database,120,2.14.0,2026-09-30
cache-prod-01,cache,,2.13.1,2026-10-30A first attempt, written the way you would write it in most languages:
# gate-naive.ps1 - first attempt: every comparison has a string on the left
$servers = Import-Csv ./servers.csv
foreach ($s in $servers) {
if ($s.FreeGB -lt 10) { "$($s.Server): low disk ($($s.FreeGB) GB)" }
if ($s.AgentVersion -lt '2.10.0') { "$($s.Server): agent too old ($($s.AgentVersion))" }
}./gate-naive.ps1cache-prod-01: low disk ( GB)It flagged the server that did not report its disk space, and waved through web-prod-02,
which has 9.5 GB free and an agent from the 2.9 line. Every value from Import-Csv is a
string, so '9.5' -lt 10 compared '9.5' with '10' as text and '2.9.3' -lt '2.10.0'
compared versions alphabetically. The empty FreeGB is the string '', which sorts before
'10'.
The fixed gate converts every value before comparing, handles the missing value explicitly,
and uses -in for the role rule:
# gate.ps1 - decide which servers are safe to deploy to
$minFreeGB = 10
$minAgent = [version]'2.10.0'
$maxPatchAge = 30
$today = Get-Date '2026-11-09' # fixed so the output is reproducible
$servers = Import-Csv ./servers.csv
foreach ($s in $servers) {
$problems = @()
# Import-Csv gives strings: convert before comparing numbers
if ([string]::IsNullOrWhiteSpace($s.FreeGB)) {
$problems += 'FreeGB not reported'
}
elseif ([double]$s.FreeGB -lt $minFreeGB) {
$problems += "only $($s.FreeGB) GB free"
}
# [version] compares 2.9.3 and 2.10.0 numerically, part by part
if ([version]$s.AgentVersion -lt $minAgent) {
$problems += "agent $($s.AgentVersion) is older than $minAgent"
}
$patchAge = ($today - [datetime]$s.LastPatch).Days
if ($patchAge -gt $maxPatchAge) {
$problems += "last patched $patchAge days ago"
}
# caches are rebuilt on deploy, so only web and database servers block
$blocking = $s.Role -in 'web', 'database'
if ($problems.Count -eq 0) {
"PASS $($s.Server)"
}
elseif ($blocking) {
"FAIL $($s.Server): $($problems -join '; ')"
}
else {
"WARN $($s.Server): $($problems -join '; ')"
}
}./gate.ps1PASS web-prod-01
FAIL web-prod-02: only 9.5 GB free; agent 2.9.3 is older than 2.10.0
FAIL db-prod-01: last patched 40 days ago
WARN cache-prod-01: FreeGB not reportedEvery operator in that script is from this article: arithmetic on dates, typed comparisons,
-in for membership, -eq 0 on a count, and a $null-safe check for missing data. The
same pattern shows up in CI pipelines (fail the build when coverage -lt 80), monitoring
scripts (alert when a certificate's NotAfter is -lt 30 days away) and audit reports
(flag accounts whose LastLogon is older than 90 days).
Common mistakes
Using > or < to compare. > silently creates a file and makes the condition false;
< stops with The '<' operator is reserved for future use. Use -gt and -lt. If a
script leaves stray files named 10 or 0 in its working directory, search it for >
inside an if.
Comparing strings that hold numbers. Import-Csv, Read-Host and $env: values are
strings, so the comparison is alphabetical:
$row = [pscustomobject]@{ Server = 'db02'; FreeGB = '9.5' }
$row.FreeGB -lt 10
[double]$row.FreeGB -lt 10
10 -gt $row.FreeGBFalse
True
TrueCast the value ([double], [int], [version], [datetime]) or put the typed value on
the left.
Using -contains as a substring test. 'web01.prod.internal' -contains 'prod' is
False with no error. -contains checks collection membership; use -like '*prod*' or
-match 'prod' for text.
Testing a filtered collection in if. if ($exitCodes -eq 0) is true or false
depending on how many zeros came back, not on whether any did. Use -contains, or
@(...).Count -gt 0. The same mechanism is why $null belongs on the left of -eq and
-ne.
Forgetting parentheses around commands. Test-Path /etc -and Test-Path /tmp fails with
A parameter cannot be found that matches parameter name 'and'. Write
(Test-Path /etc) -and (Test-Path /tmp).
Summary
- Comparison operators are words (
-eq,-gt,-like) because>and<are redirection.$x > 10creates a file named10and evaluates as false. /returns aDoubleunless the division is exact.[int]and[math]::Rounduse banker's rounding ([int]2.5is 2); useFloor,CeilingorTruncateto say what you mean.- The left operand sets the type:
'10' -lt 9is a string comparison and returnsTrue. Cast external data before comparing, and use[version]for version numbers. - String comparisons ignore case by default; the
cprefix (-ceq,-clike,-cmatch) makes them case-sensitive. - With a collection on the left, comparison operators return the matching elements, not a
boolean. Use
-contains/-infor membership and keep$nullon the left of-eq. -containsis not a substring test.-likeneeds the whole string to match its wildcard pattern;-matchsearches with a regex and fills$Matcheson success.-andand-orhave equal precedence and short-circuit;-notbinds tighter than comparisons. Parenthesise mixed conditions and any command used as an operand.-asreturns$nullinstead of throwing, but converts''and$nullto0for numeric types.
Exercises
Without running them, write down what each line returns. Then run them and explain any you got wrong using the left-operand rule and banker's rounding.
'7' + 3
7 + '3'
'7' * 3
7 / 2
[int](7 / 2)
[int](5 / 2)Show Solution
Running the six lines prints:
73
10
777
3.5
4
2A string on the left means concatenation (73) or repetition (777); a number on the left
means arithmetic (10). Division returns 3.5, and the casts round half to even: 3.5
becomes 4, but 2.5 becomes 2.
You pulled these status codes out of an access log:
$codes = 200, 201, 301, 404, 500, 502, 200, 429Using only comparison operators (no Where-Object, no loops), output every code that is an
error (400 or above), then only the client errors (400 to 499), then the number of server
errors (500 and above).
Hint
A comparison on a collection returns a collection, and you can apply another comparison to that result.
Show Solution
$codes = 200, 201, 301, 404, 500, 502, 200, 429
$codes -ge 400
$codes -ge 400 -lt 500
($codes -ge 500).Count404
500
502
429
404
429
2$codes -ge 400 -lt 500 is evaluated left to right: -ge 400 filters the array, then
-lt 500 filters the result. Wrapping the last filter in parentheses gives you an array to
call .Count on.
A deployment request asks for eu-west-1 and us-east-1. Company policy only allows
eu-west-1 and eu-central-1. First show why $allowed -contains $requested gives the
wrong answer, then print one line per requested region saying whether it is allowed.
Show Solution
$allowed = 'eu-west-1', 'eu-central-1'
$requested = 'eu-west-1', 'us-east-1'
$allowed -contains $requested
foreach ($region in $requested) {
"$region allowed: $($region -in $allowed)"
}False
eu-west-1 allowed: True
us-east-1 allowed: False-contains compares each element of $allowed with the whole $requested array as a
single object, and no element equals an array, so it is always False here. Membership has
to be tested one item at a time, with the collection on the correct side of -in.
These monitoring-agent versions are installed across a fleet. Find the ones older than 2.10.0. First try a plain string comparison and see which ones it misses, then fix it.
$installed = '2.9.3', '2.10.0', '2.14.1', '2.1.12'Show Solution
$installed = '2.9.3', '2.10.0', '2.14.1', '2.1.12'
$installed -lt '2.10.0'
$installed | Where-Object { [version]$_ -lt [version]'2.10.0' }2.1.12
2.9.3
2.1.12The string filter misses 2.9.3, because the character 9 sorts after 1. Casting each
value to [version] compares major, minor and build as numbers. (Casting the whole array,
[version[]]$installed -lt [version]'2.10.0', also filters correctly but outputs [version]
objects, which display as a table.)
On-call should be paged when CPU is above 90 or the error rate is above 5, but never during a maintenance window. Write the condition, then prove it against these four cases:
$cases = @(
@{ Cpu = 95; ErrorRate = 1; Maintenance = $false }
@{ Cpu = 40; ErrorRate = 8; Maintenance = $false }
@{ Cpu = 95; ErrorRate = 8; Maintenance = $true }
@{ Cpu = 40; ErrorRate = 1; Maintenance = $false }
)Expected: page, page, no page, no page.
Show Solution
$cases = @(
@{ Cpu = 95; ErrorRate = 1; Maintenance = $false }
@{ Cpu = 40; ErrorRate = 8; Maintenance = $false }
@{ Cpu = 95; ErrorRate = 8; Maintenance = $true }
@{ Cpu = 40; ErrorRate = 1; Maintenance = $false }
)
foreach ($c in $cases) {
$page = ($c.Cpu -gt 90 -or $c.ErrorRate -gt 5) -and -not $c.Maintenance
"cpu=$($c.Cpu) err=$($c.ErrorRate) maint=$($c.Maintenance) -> page=$page"
}cpu=95 err=1 maint=False -> page=True
cpu=40 err=8 maint=False -> page=True
cpu=95 err=8 maint=True -> page=False
cpu=40 err=1 maint=False -> page=FalseThe parentheses make the grouping explicit. Without them the expression happens to work in
PowerShell, because -or and -and are evaluated left to right, but the same text in C or
Python would group as cpu || (err && !maint) and page during maintenance. Parentheses make
the rule correct in your head as well as in the shell. Testing a condition against a table
of cases like this is a cheap habit that catches precedence bugs before production does.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2), November 2026. Every example was
run by piping it into pwsh -NoProfile, so errors appear as they do at an interactive
prompt; the two scripts were run from files. I also spot-checked the rounding, string
comparison, precedence and -as results in Windows PowerShell 5.1 on Windows 11 and got
identical answers. The surprise while testing was the first example: if ($freeGB > 10) did
not fail at all, it just created a file named 10.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.