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

September 18, 2026 3 answers
Asked by hedge__clippers
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?

Answers

!careful there+
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.
Reply to this answer
revisit this
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.

POTLUCK ROSTER: 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.

Reply to this answer
_apricot preserves
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.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions