我需要使用PowerShell -Command"&scriptname"运行一个脚本,如果我从PowerShell返回的退出代码与脚本本身返回的退出代码相同,我真的很喜欢它.不幸的是,如果脚本返回0,则PowerShell返回0;如果脚本返回任何非零值,则PowerShell返回1,如下所示:
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>
Run Code Online (Sandbox Code Playgroud)
使用[Environment] :: Exit(42)几乎可以正常工作:
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>
Run Code Online (Sandbox Code Playgroud)
除了脚本以交互方式运行时,它将退出整个shell.有什么建议?