Home > front end >  Get exitcode from powershell invoke-command from linux
Get exitcode from powershell invoke-command from linux

Time:10-17

/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. The invoke-command is connecting with ssh. The last line of check.ps1 is "Exit 2". But exit code alway return 0. Any suggestions to get the correct exit code? I would like to use this command as Nagios check.

CodePudding user response:

Unfortunately, as of PowerShell 7.2, any out-of-runspace code, notably including remoting calls, does not relay script / process exit codes.

Therefore, your script's exit 2 command has no effect on the exit code reported by the /usr/bin/pwsh process.

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.

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.

CodePudding user response:

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. This is from cmd, but I believe the effect is the same.

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
  • Related