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:est> cat foo.ps1
exit 42
PS C:est> ./foo.ps1
PS C:est> echo $lastexitcode
42
PS C:est> powershell -Command "exit 42"
PS C:est> echo $lastexitcode
42
PS C:est> powershell -Command "& ./foo.ps1"
PS C:est> echo $lastexitcode
1
PS C:est>
Using [Environment]::Exit(42) almost works:
PS C:est> cat .az.ps1
[Environment]::Exit(42)
PS C:est> powershell -Command "& ./baz.ps1"
PS C:est> echo $lastexitcode
42
PS C:est>
Except that when the script is run interactively, it exits the whole shell. Any suggestions?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…