The exit
statements in your code cause your script to exit before it gets to the point where $exit
would be written to the output file. But even if it got there it wouldn't actually record the exit code, because the exit
keyword doesn't magically fill the (undefined) variable $exit
with the exit code. You may be confusing it with the automatic variable $LastExitCode
, which gets updated on the caller side after the callee exited.
What you actually want to do is define a custom function that properly sets the exit code and does everything else you want to do before actually exiting:
function ExitWithCode($exitcode) {
$host.SetShouldExit($exitcode)
$exit | Out-File -FilePath 'C:\stuff\PSOutput.txt'
exit $exitcode
}
then use it in your code like this:
try {
[IO.File]::OpenWrite($file).Close()
ExitWithCode 0
} catch {
ExitWithCode 999
}
Using $host.SetShouldExit()
in addition to exit
ensures that your script always sets the proper exit code, regardless of how it's invoked.