PowerShell with a Purpose Blog

Capturing Errors (and Variable Names)

Received an email from a reader this morning, who asked, "is there a way to capture whatever error occurs when running a cmdlet? I've tried using the -ErrorVariable parameter, but it doesn't work." He included an example of what he's doing:

Get-WmiObject Win32_LogicalDisk -computer $computername -errorvariable $error

First, the -ErrorVariable parameter (or its alias, -EV) works perfectly for capturing errors - it's just not being used quite right in this example. The $error variable isn't a good one to use, because it's actually pre-defined by PowerShell. It's a collection of all the errors that have occurred in the shell, with the first error ($error[0]) being the most recent. Try picking another variable, like $MyErr, to use with -EV.

Second, when you provide a variable name to a cmdlet parameter, you don't use the $. The $ isn't technically part of the variable name. Rather, $ is a cue to the shell that what follows is a variable name, and that you want to use the contents of the variable. So if you did this:

Get-WmiObject Win32_LogicalDisk -computer $computername -errorvariable $MyErr

Then you're telling PowerShell to get the contents of $MyErr, and to use those contents as the name of the variable to capture the error into. If $MyErr is empty, that command would generate an error for that reason - you've specified an empty error variable name. The correct usage is this:

Get-WmiObject Win32_LogicalDisk -computer $computername -errorvariable MyErr

This will create a variable named MyErr (if it doesn't exist in the current scope), and capture any Get-WmiObject errors into it. You can access those by using $MyErr:

Try {
  Get-WmiObject Win32_LogicalDisk -computer $computername -errorvariable MyErr -erroraction Stop
} catch {
  "$MyErr" | Out-File c:\errors.txt -append
}

This example added -ErrorAction to the command, so that any non-terminating errors would become full, terminating exceptions that could be trapped. Within the Catch block, which will execute if an exception is thrown, I'm simply logging the error. Note that I didn't need to use the quotation marks, but doing so demonstrates that double quotes are special. Within them, PowerShell will look for that $ cue, and replace the variable reference with its contents.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish