-command 的退出代码与脚本的退出代码不同 [英] -command's exit code is not the same as a script's exit code

查看:42
本文介绍了-command 的退出代码与脚本的退出代码不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 PowerShell -Command "& scriptname" 运行脚本,如果我从 PowerShell 返回的退出代码与脚本本身返回的退出代码相同,我真的很喜欢它.不幸的是,如果脚本返回 0,PowerShell 返回 0,如果脚本返回任何非零值,则返回 1,如下所示:

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>

使用 [Environment]::Exit(42) 几乎可以工作:

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>

除了当脚本以交互方式运行时,它会退出整个 shell.有什么建议吗?

Except that when the script is run interactively, it exits the whole shell. Any suggestions?

推荐答案

如果您将发送到 -Command 的部分作为脚本查看,您会发现它永远不会工作.运行 foo.ps1 脚本的脚本没有退出调用,因此它不会返回退出代码.

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.

如果您确实返回退出代码,它将执行您想要的操作.还将其从 " 更改为 ',否则 $lastexitcode 将在您将字符串发送"到第二个 PowerShell 之前解析,如果您运行它来自 PowerShell.

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:如果您只想运行脚本,还可以查看 -File 参数.但也要知道,如果您遇到 -Command 那样的终止错误,它不会 return 1.请参阅此处了解有关最后一个主题的更多信息.

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

这篇关于-command 的退出代码与脚本的退出代码不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆