How to Capture Exit Codes in Remote PowerShell Execution?

0
2
Asked By CleverPenguin42 On

I'm trying to run some PowerShell commands remotely using SSH. My client is a Linux Docker container with PowerShell 7.4 within a self-hosted GitLab runner, and I'm connecting to a Windows Server 2019 that's running PowerShell 5.1.

My goal is to ensure that if my remote PowerShell script fails, I can capture the appropriate exit code to trigger a pipeline failure. However, I'm having trouble getting PowerShell to return the desired exit code. Here's a snippet of my latest attempt:

```
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

trap {
exit 42
}

Write-Host $env:HOSTNAME
Set-Location E:/does-exit; # this works fine
Set-Location E:/does-not-exist; # this should throw an error
exit 0; # should exit cleanly if everything is fine
```

In this case, the script fails, and I see that `$LASTEXITCODE` is 1, but I expected to see 42. However, when I use a try/catch block instead, I can successfully return the desired exit code:

```
try {
Set-Location E:/does-not-exist
}
catch { exit 42 }
```

I'm confused about why the trap isn't functioning as expected. Is this issue related to the version difference between PowerShell 7.4 on my client and PowerShell 5.1 on the remote machine? Also, I need to find a better way to pass the password to prevent any logging issues; any suggestions would be appreciated!

1 Answer

Answered By TechSage88 On

The trap is firing, but when a terminating error occurs, PowerShell itself forces the process to exit with code 1. In PowerShell 5.1, this host behavior overrides your exit code in the trap. So even if you command `exit 42`, the host reports 1 back to SSH because it sees the script as having failed due to an unhandled error.

With try/catch, the error never reaches the host. It’s handled within the script, which means when you call `exit 42` in the catch block, that’s the actual process exit code. So, yeah, using try/catch is the way to go here!

CuriousCoder77 -

Thanks for the breakdown! I'm wondering if switching to PowerShell 7.4 on the server will help with this issue. If I set up PowerShell Remoting over SSH, would that still have similar error handling limitations?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.