简体   繁体   English

从 linux 的 powershell invoke-command 获取退出代码

[英]Get exitcode from powershell invoke-command from linux

/usr/bin/pwsh -command Invoke-Command -Hostname PC -UserName boss -FilePath ./check.ps1 -ArgumentList "A","25","10"

So I am running this command from Ubuntu with bash shell.所以我正在使用 bash shell 从 Ubuntu 运行这个命令。 The invoke-command is connecting with ssh. invoke-command 正在与 ssh 连接。 The last line of check.ps1 is "Exit 2". check.ps1 的最后一行是“Exit 2”。 But exit code alway return 0. Any suggestions to get the correct exit code?但是退出代码总是返回 0。有什么建议可以获得正确的退出代码吗? I would like to use this command as Nagios check.我想将此命令用作 Nagios 检查。

Unfortunately, as of PowerShell 7.2, any out-of-runspace code, notably including remoting calls, does not relay script / process exit codes.不幸的是,从 PowerShell 7.2 开始,任何超出运行空间的代码,特别是包括远程调用,都不会中继脚本/进程退出代码。

Therefore, your script's exit 2 command has no effect on the exit code reported by the /usr/bin/pwsh process.因此,脚本的exit 2命令对/usr/bin/pwsh进程报告的退出代码没有影响。

Even inside the PowerShell session this exit code isn't available for out-of-runspace calls [1] , so - unfortunately - your only option is to make your script output the desired exit code, make the PowerShell session capture it, and relay with an exit call that is a direct part of the PowerShell code passed to the CLI's -command parameter.即使PowerShell 会话中,此退出代码也不适用于运行空间外调用[1] ,因此 - 不幸的是 - 您唯一的选择是让您的脚本输出所需的退出代码,让 PowerShell 会话捕获它,然后中继exit调用是传递给 CLI 的-command参数的 PowerShell 代码的直接部分。

In the simplest case, if you modify your script to output the desired exit code and assuming that that exit code is the script's only output, you can use:在最简单的情况下,如果您修改脚本以输出所需的退出代码并假设该退出代码是脚本的唯一输出,则可以使用:

/usr/bin/pwsh -command 'exit (Invoke-Command -Hostname PC -UserName boss -FilePath ./check.ps1 -ArgumentList A, 25, 10)'

[1] For in-runspace calls, the exit code set by scripts that use exit as well as by external programs (processes) is reflected in the automatic $LASTEXITCODE variable . [1] 对于运行空间内调用,由使用exit脚本以及外部程序(进程)设置的退出代码反映在自动$LASTEXITCODE变量中

For what it's worth, I believe if your script has an exception, the exit code will be non-zero.对于它的价值,我相信如果您的脚本有异常,退出代码将是非零的。 For example, my check.ps1 just has "get-childitem foo" where foo doesn't exist.例如,我的 check.ps1 只有“get-childitem foo”,其中 foo 不存在。 This is from cmd, but I believe the effect is the same.这是来自cmd,但我相信效果是一样的。

pwsh -command Invoke-Command -computername localhost check.ps1 -args A,25,10
Get-ChildItem: Cannot find path 'C:\Users\js\Documents\foo' because it does not exist.

echo %errorlevel%
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM