- 1 year ago
GitHubActions on Windows host (powershell?): exit code of previous lines being ignored
In GitHub Actions, when using PowerShell on a Windows host, the exit code of each line is not automatically propagated to subsequent lines. By default, each line in a PowerShell script is treated as an independent command, and the execution continues regardless of the exit code.
To ensure that the exit code of each line is considered and that the execution stops if a previous line fails, you can use the $ErrorActionPreference
variable and the Exit
statement.
Here's an example of how you can achieve this:
yamlname: PowerShell Example
on: [push]
jobs:
build:
runs-on: windows-latest
steps:
- name: Set up PowerShell
uses: actions/setup-powershell@v1
- name: Run PowerShell script
shell: powershell
run: |
$ErrorActionPreference = "Stop"
# Command 1
Some-Command1
if ($LastExitCode -ne 0) { Exit $LastExitCode }
# Command 2
Some-Command2
if ($LastExitCode -ne 0) { Exit $LastExitCode }
# Command 3
Some-Command3
if ($LastExitCode -ne 0) { Exit $LastExitCode }
# ... additional commands
In the example above, each command (Some-CommandX
) is followed by an if
statement that checks the $LastExitCode
. If the exit code is non-zero, it means that the previous command failed. In that case, we use the Exit
statement to stop the execution of the script and propagate the non-zero exit code.
By setting the $ErrorActionPreference
to "Stop"
, any error that occurs in a command will cause an exception, which can be caught by the if
statement and trigger the Exit
statement.
Note that this approach explicitly checks the exit code of each command and handles it within the script. Alternatively, you can use the set -e
option at the beginning of a Bash script to achieve a similar behavior of terminating the script if any command fails, but this method is specific to Bash and not applicable to PowerShell.