[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Using try catch blocks in Powershell

Posted on 2011-04-26
5
Medium Priority
?
1,479 Views
Last Modified: 2012-05-11
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?
0
Comment
Question by:YZlat
  • 3
5 Comments
 
LVL 16

Assisted Solution

by:ToddBeaulieu
ToddBeaulieu earned 252 total points
ID: 35469372
try/catch is part of v2. Are you using v2 or the original v1?
0
 
LVL 35

Author Comment

by:YZlat
ID: 35469546
v1

is there a way to catch errors in v1?
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 35469631
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
 
LVL 18

Accepted Solution

by:
Learnctx earned 248 total points
ID: 35471854
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
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 35474134
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will be converting StringData saved within a text file into a hash table. This can be further used in a PowerShell script for replacing settings that are dynamic in nature from environment to environment.
Transferring FSMO roles is done when an admin wants to split roles between certain Domain Controllers or the Domain Controller holding the Roles has been forcefully demoted using dcpromo / forceremoval
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Loops Section Overview

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question