May 31st, 2018

PowerTip: Ensure that errors in PowerShell are caught

Doctor Scripto
Scripter

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

 

 

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.