PowerShell is an awesome technology. It has become an essential tool for doing automated deployments with Team Foundation Server 2010. Creating deployment scripts in PowerShell are very easy to manage and maintain by the entire development without having to know about the details of the build definitions. In future posts, I will explain how I use the build definitions and PowerShell to perform the deployments. With this post I wanted to share a small tip on being able to catch all errors with a Try, Catch.
In PowerShell, there are two types of errors. Terminating errors and non-terminating errors. Terminating errors will automatically be caught in a Try, Catch block but non-terminating errors will not. Look at this example below.
try { copy-item "c:\notexists\file.txt" "c:\temp" } catch { write-host "bad copy" }
try { copy-item "c:\notexists\file.txt" "c:\temp" } catch {
write-host "bad copy"
}
This command looks like it should write to the out the error message because the folder and file do not exists. However when you run this, it will only display the PowerShell error message.
Copy-Item : Cannot find path 'C:\notexists\file.txt' because it does not exist. At C:\temp\copyitem.ps1:3 char:14 + copy-item <<<< "c:\notexists\file.txt" "c:\temp" + CategoryInfo : ObjectNotFound: (C:\notexists\file.txt:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
This is an example of a non-terminating error. There are two ways to fix this. The –ErrorAction ”Stop” flag can be added to many of cmdlets.
copy-item "c:\notexists\file.txt" "c:\temp" -ErrorAction "Stop"
Now, when the script is run, it will display the error message, “bad copy”.
This is great but if you are like me, you don’t want to have to add this to every command. Luckily there is a way to do this for the entire script. At the beginning of the script, you can set $ErrorActionPreference = “Stop”. If you want to be able to toggle it, it default setting is “Continue”.
$ErrorActionPreference = "Stop"
Here is the final script. Enjoy!
$ErrorActionPreference = "Stop" try { copy-item "c:\notexists\file.txt" "c:\temp" } catch { write-host "bad copy" }
Remember Me
a@href@title, strike
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.