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