Jan 032011
 

While writing Powershell scripts you often want to know what types of errors are occurring within your scripts and deal with them appropriately. Powershell give several ways to track errors but one of the lesser known ones is the “Dollar Hook”. This is a variable that always exists and holds a variable stating whether the last command ended with an error or not. This is useful because instead of setting up a generic trap you can deal with a specific command that you know has a good chance of failing. Take this example:

Get-Process "ANonExistantProcess" -ErrorAction SilentlyContinue
$?
>>False

So how do you use it to deal with an error? Well that is easy, you can now run an “if” statement on it.

Get-Process "ANonExistantProcess" -ErrorAction SilentlyContinue
IF (!$?){ "There was an error!" }
>>There was an error!

Also, if you really want to look for a very specific error there is another variable that holds the exact output: $lastexitcode. This guy works just like the errorlevel idea in DOS. When you run a command the error number is stored in the variable where 0 is success.

ping "ANonExistantComputer"
$LastExitCode
>>1

Given that, there are a lot of commands that don’t support this notation, so I would just use a dollar hook and then check for your number by looking into the $error[0] variable at that time.

This gives us the tools, but know there are some annoying restrictions. First Dollar Hooks use the last COMMAND, so if you want to test for something that throws an error but isn’t a command, tuff luck. Try it with a divide by zero error, it won’t work. Next the $LastExitCode variable has to be supported by the command itself. A lot of times you’ll know that the command threw an error and what error number, but the return code will still be 0 (success). This is especially true for errors that are non-terminating errors.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">