Using try catch blocks in Powershell

I tried using try-catch blocks in powershell and I got an error "try is not recognized as cmdlet". Is there a snap-in I need to add for it to work?
LVL 35
YZlatAsked:
Who is Participating?
 
LearnctxConnect With a Mentor EngineerCommented:
Trap is the equivalent of try/catch in v2. It is fairly easy to implement, but there is not the greatest documentation for it. An example of using it:
Function Trap-Test
{
   trap { $_.Exception.Message ; Continue }
   "Before the error"
   Get-WmiObject Win32_Process -ComputerName ThisComputerDoesNotExist -EA Stop
   "After the error"
}

Open in new window

Another example is for example accessing a registry value on a remote machine.
$computer = "computer/server you have no access to or that does not exist"
function trap-test
{
	$key = "SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}"
	$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $computer)
	$regkey = $reg.OpenSubkey($key)

	## Error handling section
	trap [System.IO.IOException]
	{
		"Path not found"
		Continue
	}
	trap [System.Security.SecurityException]
	{
		"Access Denied"
		Continue
	}
	trap
	{
		"Generic trap"
		Continue
	}
}

Open in new window

Once you play with it a little bit, it is fairly easy to use trap in POSH v1. Try/Catch in v2 is my preferred way though, but trap is good if you don't have v2 available. If you want more info just Google for powershell and trap, you will find some blogs with good info.
0
 
ToddBeaulieuConnect With a Mentor Commented:
try/catch is part of v2. Are you using v2 or the original v1?
0
 
YZlatAuthor Commented:
v1

is there a way to catch errors in v1?
0
 
ToddBeaulieuCommented:
Yes. With the trap syntax. I recommend upgrading. V2 is smoother. we put off upgrading and then found zero issues when we did.

Error handling is tricky business in ps!
0
 
ToddBeaulieuCommented:
I'm not debating that it's easy to implement error handling in PS in *theory*.

I'll whole heatedly debate that it's easy to implement it reliably in practice.  

To have fun, I decided to code an application using PS that I'd normally have used c# to do. It collects files from an FTP site, decrypts them, decompresses them, audits that they have valid contents, logs them in a SQL database and then moves them to an appropriate folder.

Let me tell you that it took considerable effort to "get it right" with the error handling. There are some gotchas that will getcha! So be prepared to experiment if your intention is to write a reliable application that your business can ... well, rely on.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.