PowerTip: Ensure that errors in PowerShell are caught

Doctor Scripto

Dr Scripto

Summary: Here’s how to make sure your errors get caught with Try Catch Finally.

   Hey, Scripting Guy! I’ve been trying to use the Try Catch Finally, but some of my errors aren’t getting caught. What could be the cause?

   For Try Catch Finally, you need to make sure the error defaults to a “Stop” action for the cmdlet in question. Here’s a quick example:

try

{

Get-Childitem c:\Foo -ErrorAction stop

}

catch [System.Management.Automation.ItemNotFoundException]

{

'oops, I guess that folder was not there'

}

 

Drawing of Dr. Scripto

 

 

0 comments

Comments are closed. Login to edit/delete your existing comments