Using ErrorVariable

Another common parameter you might want to include in your PowerShell code is -ErrorVariable. Like -OutVariable that I talked about yesterday, you can redirect error information to a specified variable:

gwmi win32_operatingsystem -errorvariable oops |out-null

In this situation, $oops will have no value since no error was returned. But what about this where $computer is a remote computer that you’ve mistyped, don’t have permission for or is down:

gwmi win32_operatingsystem -computer $computer -errorvariable oops |out-null

Now if you look at $oops you’ll see the error message. Any errors are still recorded in the default $error variable. $oops is an error record as you can see:

Mon 1/22/2007 12:25:15 PM PS S:\ > $oops |gm


TypeName: System.Management.Automation.ErrorRecord

Name MemberType Definition
---- ---------- ----------Equals Method System.Boolean Equals(Object obj)GetHashCode Method System.Int32 GetHashCode()GetObjectData Method System.Void GetObjectData(Serialization..GetType Method System.Type GetType()get_CategoryInfo Method System.Management.Automation.ErrorCateg..get_ErrorDetails Method System.Management.Automation.ErrorDetai..get_Exception Method System.Exception get_Exception()get_FullyQualifiedErrorId Method System.String get_FullyQualifiedErrorId()get_InvocationInfo Method System.Management.Automation.Invocation..get_TargetObject Method System.Object get_TargetObject()set_ErrorDetails Method System.Void set_ErrorDetails(ErrorDetai..ToString Method System.String ToString()CategoryInfo Property System.Management.Automation.ErrorCateg..ErrorDetails Property System.Management.Automation.ErrorDetai..Exception Property System.Exception Exception {get;}
FullyQualifiedErrorId Property System.String FullyQualifiedErrorId {
get;
InvocationInfo Property System.Management.Automation.Invocation..
TargetObject Property System.Object TargetObject {
get;}

It’s not apparent, but this is an array that should only have a single member. So if you wanted to see the exception you would use code like this:

$oops[0].Exception

If you were adding error handling to handle different error codes you’ll want to use something like this:

($oops[0].Exception).errorcode

For the RPC server unavailable error you would see -2147023174

Defining your own error variables gives you some additional flexibility for your PowerShell scripts and expressions.

Technorati tags: , , ,