Continuous Learning and Sharing of Team Foundation Server and Application Lifecycle Management RSS 2.0
# Saturday, July 02, 2011

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"

}

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"

}

 

Saturday, July 02, 2011 10:14:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [0] -
PowerShell | Team Build 2010

Visual Studio ALM MVP
Microsoft Visual Studio ALM MVP
Archive
<July 2011>
SunMonTueWedThuFriSat
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Mike Douglas
Sign In
Statistics
Total Posts: 76
This Year: 0
This Month: 0
This Week: 0
Comments: 53
All Content © 2012, Mike Douglas
DasBlog theme 'Business' created by Christoph De Baene (delarou)