Does `if ($thing)` differ from `if (-not $thing)` in PowerShell?

0
2
Asked By MellowOrbit42 On

When checking whether a command returned something and using exit codes, is there any meaningful difference between these two forms?

$thing = Get-Thing

if ($thing) {
Exit 1
} else {
Exit 0
}

Alternatively:

if (-not $thing) {
Exit 0
} else {
Exit 1
}

Are they equivalent apart from readability, or can their performance or behavior differ in larger or more complex scripts?

3 Answers

Answered By CedarFox7 On

For the same value, these conditions are logical opposites, so the two examples produce the same exit code. The performance difference would be negligible compared with running the command and the rest of PowerShell's execution machinery. Choose the form that makes the intended condition easiest to read.

Answered By VelvetKite_19 On

The important detail is what PowerShell considers truthy. A variable can contain $null, $false, 0, an empty string, a nonempty string, or an array, and those values are converted to Boolean when used in an if statement. The result depends on the value returned by Get-Thing, but negating the condition still reverses that Boolean result; it does not perform a different kind of presence check.

BrightMango6 -

So the main thing to verify is the shape and contents of Get-Thing's output. If you need to distinguish cases such as no result, one result, or multiple results, test those cases explicitly instead of relying only on general truthiness.

Answered By QuietPebble88 On

If the only purpose is to return opposite exit codes, you can also make the relationship more direct, such as `if ($thing) { exit 1 } else { exit 0 }`, or calculate the status from the Boolean condition. There is no general rule that one ordering is faster; use whichever condition communicates the desired behavior most clearly.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.