PowerShell Scripts, Tips, Expert Advice & Training, Forums, and Resources

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Blog Posts

01-27-2012 - PowerShell Deep Dive 2012
01-27-2012 - Restricting a user’s computers
01-27-2012 - Friday Fun Get Content Words

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Catching Errors

In forums, people often get confused with error handling. For example, this code does not call the error handler. Instead, the red PowerShell error message pops up:

try { Remove-Item \\$name\c$\windows\temp\filename.exe }
catch {Write "Not able to access files on $name"}

When you want to catch errors produced by cmdlets, always make sure you add the parameter -ErrorAction Stop to it. Only then will the cmdlet emit an exception that your script can handle. So this works:

try { Remove-Item \\$name\c$\windows\temp\filename.exe -ErrorAction Stop }
catch {Write "Not able to access files on $name"}

If you want error handling for all cmdlets, you can also change the default mode like this:

$ErrorActionPreference = 'Stop'

Twitter This Tip! ReTweet this Tip!

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.