PowerShell Script tasks in Bamboo will not follow the script's return code
Platform notice: Server and Data Center only. This article only applies to Atlassian products on the Server and Data Center platforms.
Support for Server* products ended on February 15th 2024. If you are running a Server product, you can visit the Atlassian Server end of support announcement to review your migration options.
*Except Fisheye and Crucible
Summary
Running PowerShell scripts in Bamboo will always exit with 0, even if the invoked script returns a non-zero value
Environment
- Any Bamboo version
- Powershell Script tasks (Builds & Deployments)
Diagnosis
When running a PowerShell script task that invokes an Invoke-Command cmdlet, the Script task will always succeed in Bamboo, even if the script clearly fails and returns a non-zero exit code.
Cause
Bamboo will create a PS1 script with the commands assigned to the Script Task and run them. The script task will be executed on the Agent as:
powershell -NonInteractive -ExecutionPolicy bypass -Command C:\temporary\location\of\the\script.ps1]
As the invoked PS1 script content may invoke a second script via Powershell's Invoke-Command cmdlet, that will result in the exit code not being passed to the script's main shell, thus the Script task will always exit with success unless forced. That's by PowerShell's design and can't be changed, but there are workarounds that can be implemented.
Solution
Choosing the code that best suits you will be up to each customer, check the examples below for some ideas on how to force the $LastExitCode
to be passed to the main PowerShell session. For example:
Invoke-Command -ScriptBlock {
Command123 --options --setting 456
}
If ($LastExitCode -ne 0) {
Exit $LastExitCode
}
Another example:
$ExitCode = Invoke-Command -ScriptBlock {
Command123 --options --setting 456
Return $LastExitCode
}
Exit $ExitCode
Please check the following public links for more ideas:
- Stack Overflow - catching return code of a command with "invoke-command" - Powershell 2
- Stack Overflow - How to capture the Return Value of a ScriptBlock invoked with Powershell's Invoke-Command
- Microsoft Learn - powershell How do I capture a return code from a script I run on a remote computer
- Reddit - Capture exit code to Invoke-Command on remote machine?