When checking whether a command returned something and then choosing an exit code, is there any meaningful difference between testing for a truthy value and testing for its absence? For example:
$thing = Get-Thing
if ($thing) {
exit 1
} else {
exit 0
}
Compared with:
if (-not $thing) {
exit 0
} else {
exit 1
}
Are these equivalent apart from readability, or can the choice affect performance or logic in larger or more complex scripts?
3 Answers
For a scalar value, those two versions are logically equivalent: both evaluate `$thing` once, and `-not` simply reverses its Boolean interpretation. Any performance difference would be negligible compared with the command being run and the rest of PowerShell's execution overhead. Choose the form that makes the intended condition easiest to read. In practice, it is often clearer to test the success or failure case directly and use the conventional exit-code meaning: `0` for success and a nonzero value for failure.
The important issue is what `Get-Thing` returns. PowerShell converts different values to Boolean differently: `$null`, `$false`, `0`, and an empty string are false, while most nonempty strings and objects are true. Arrays also have special behavior: an empty array is false, but a nonempty array is generally true, even if some of its elements are false or null. So the two shown conditions still negate each other, but you should make sure PowerShell's truthiness rules match what you actually mean by 'found.' If you need to distinguish `$null`, an empty collection, or a particular property, test that explicitly.
Negated conditions can sometimes be harder to scan, especially when they contain several clauses. If the main branch represents the normal or successful case, writing that case positively is usually easier to maintain. There is no general rule that putting exit code `0` first makes the script faster or more correct; use whichever structure communicates the intended result most clearly.

So the returned object or collection matters more than whether the condition is written positively or negatively. For example, checking `$null -eq $thing` or testing `.Count` can be clearer when an empty result has a specific meaning.