A quick note about exit codes from powershell

This may be an extreme edge case, but since I spent a few hours on something rather trivial, I though I should share it. When running Invoke-Command from powershell invoked via command line – be wary of the curly braces.

What is the difference between the following two commands?

powershell.exe -Command "& {invoke-command {throw 'error'}}"

powershell.exe -Command "& invoke-command {throw 'error'}"

As it turns out, the first one will exit with error code 0, the second one will exit with error code 1. This in turn is very important if you want to integrate some powershell command into your build process, and want to make sure that the build does or does not fail if the invoked command fails. An example from real life would be stopping and starting a web server, such as

powershell.exe -Command "& invoke-command -ComputerName MYSERVER {Import-Module WebAdministration; Stop-Website Default}"

In my case I needed to do automatic deploy to a web server from a CI system, and thus it was important to mark the build as failed if my commands to the web server didn’t get through. Since I am somewhat of a beginner to powershell, it took a while to find that wrapping the command in curly braces was the cause.

I hope this is of some use if you find your build succeeding even though your powershell commands failed.

Leave a Reply

Close Menu