r/PowerShell • u/RandomSkratch • Sep 21 '26
Solved Is there a difference between If $thing vs If -not $thing in terms of speed or proper formatting?
In the case of looking for the presence of something and using If paired with Exit codes, what's the difference between looking for the presence vs absence? For example
$Thing = Get-Thing
if ($thing) {
Exit 1
}
Else {
Exit 0
}vs
if (-not $thing) {
Exit 0
}
Else {
Exit 1
}Is it just for readability (ie 0 comes before 1 because it's in sequence?) Or are there speed differences or logic handling differences that matter in more complex scenarios?
Solved
Depends on the results of $thing determine whether or not you need to test for true or false. Speed isn't really a factor.
29
Upvotes
15
u/Pixelgordo Sep 21 '26
Make a loop long enough to apply measure-command and look for differences
6
u/DonL314 Sep 21 '26
Careful! Note that some values for $thing could give true both for ($thing) and (-not $thing) !!
Try this:
$thing = @($null, 'some', $false)
I think that will give you funny results.
2
u/purplemonkeymad Sep 21 '26
I prefer:
It keeps the indentations down making it easier to read, especially if you have a bunch of validations to do.
4
u/theomegachrist Sep 22 '26
It doesn't matter. I use the one that makes logical sense if a person is reading my script
1
u/uptimefordays Sep 21 '26
I often approach conditional logic from the perspective of a never nester. Basically I want to use guard clauses to prevent nesting logic as much as possible. I find it helps keep code simple and understandable.
Therefore I’d use whichever approach best simplifies your happy path.
2
u/aleques-itj Sep 21 '26
In Powershell, maybe. My guess would be the typing makes it need more work.
It could be null, 0, a string, an array, etc.
No idea off the top of my head if this will vanish if you deliberately type everything.
It's probably vanishingly small compared to all the other language machinery in play.
2
u/sccm_sometimes Sep 25 '26
When Powershell casts a String to a Boolean it will result in
$truefor everything except empty '' strings.2
u/Meignent-Takeko Oct 16 '26
no perf difference. one thing worth noting though, be careful with what Get-Thing actually returns. if it can return an empty collection vs $null those can behave differently in a boolean check
1
u/CyberChevalier Sep 22 '26
It’s mostly why I never use that but :
If ($true -eq $Thing)
Because thing can be a nullable Boolean or a string or whatever and you are not casting it as a Boolean
Try this
$true -eq “hello” => true
“Hello” -eq $true => false
The first assume the test is about a Boolean test and try to cast “hello” as a Boolean (which return true)
The second assume the test is a string test and convert the $true to a string (which return “true”)
Even If you want to test if something is not null use
$null -ne $Thing