edi*_*ven 27 powershell exit-code
我需要使用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.有什么建议?
Lar*_*ens 31
如果您将要发送的部分-Command视为脚本,您将看到它永远不会起作用.运行foo.ps1脚本的脚本没有退出调用,因此它不会返回退出代码.
如果您确实返回退出代码,它将执行您想要的操作.同时将其更改"为',否则$lastexitcode将在您将字符串'发送'到第二个PowerShell之前解决,如果您从PowerShell运行它.
PS C:\test> powershell -Command './foo.ps1; exit $LASTEXITCODE'
PS C:\test> echo $lastexitcode
42
Run Code Online (Sandbox Code Playgroud)
PS:-File如果您只想运行脚本,还要检查参数.但是,return 1如果你有终止错误,也知道它-Command不会.见这里要了解他们最后一个话题.
PS C:\test> powershell -File './foo.ps1'
PS C:\test> echo $lastexitcode
42
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73699 次 |
| 最近记录: |