07-21-2023, 09:01 PM
**Treating the ExitCode of a Process as a Boolean.**
eg, with this code:
$p = Start-Process foo.exe -NoNewWindow -Wait -PassThru
if ($p.ExitCode) {
# handle error
}
things are good, unless say foo.exe doesn't exist or otherwise fails to launch.
in that case `$p` will be `$null`, and `[bool]($null.ExitCode)` is False.
a simple fix is to replace the logic with `if ($p.ExitCode -ne 0) {}`,
however for clarity of code imo the following is better: `if (($p -eq $null) -or ($p.ExitCode -ne 0)) {}`
eg, with this code:
$p = Start-Process foo.exe -NoNewWindow -Wait -PassThru
if ($p.ExitCode) {
# handle error
}
things are good, unless say foo.exe doesn't exist or otherwise fails to launch.
in that case `$p` will be `$null`, and `[bool]($null.ExitCode)` is False.
a simple fix is to replace the logic with `if ($p.ExitCode -ne 0) {}`,
however for clarity of code imo the following is better: `if (($p -eq $null) -or ($p.ExitCode -ne 0)) {}`