I need to run a script with PowerShell -Command "& scriptname", and I would really like it if the exit code I got back from PowerShell was the same as the exit code the script itself returned. Unfortunately, PowerShell returns 0 if the script returns 0, and 1 if the script returns any non-zero value as illustrated below:
PS C:\test> cat foo.ps1 exit 42 PS C:\test> ./foo.ps1 PS C:\test> echo $lastexitcode 42 PS C:\test> powershell -Command "exit 42" PS C:\test> echo $lastexitcode 42 PS C:\test> powershell -Command "& ./foo.ps1" PS C:\test> echo $lastexitcode 1 PS C:\test>
Using [Environment]::Exit(42) almost works:
PS C:\test> cat .\baz.ps1 [Environment]::Exit(42) PS C:\test> powershell -Command "& ./baz.ps1" PS C:\test> echo $lastexitcode 42 PS C:\test>
Except that when the script is run interactively, it exits the whole shell. Any suggestions?
An exit code is a system response that reports success, an error, or another condition that provides a clue about what caused an unexpected result from your command or script. Yet, you might never know about the code, because an exit code doesn't reveal itself unless someone asks it to do so.
All builtins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments.
Exit code 1 indicates a general failure. Exit code 2 indicates incorrect use of shell builtins. Exit codes 3-124 indicate some error in job (check software exit codes) Exit code 125 indicates out of memory. Exit code 126 indicates command cannot execute.
If you look at the part you are sending to -Command
as a script you will see it would never work. The script running the foo.ps1
script does not have a call to exit, so it does not return an exit code.
If you do return an exit code it will do what you want. Also change it from "
to '
, otherwise $lastexitcode
will be resolved before you 'send' the string to the second PowerShell, if you run it from PowerShell.
PS C:\test> powershell -Command './foo.ps1; exit $LASTEXITCODE' PS C:\test> echo $lastexitcode 42
PS: Also check out the -File
parameter if you just want to run a script. But also know it does not return 1
if you have a terminating error as -Command
does. See here for more on that last topic.
PS C:\test> powershell -File './foo.ps1' PS C:\test> echo $lastexitcode 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With