PowerShell

PowerShell: Error Handling with $Error

The $Error Variable in PowerShell contains all error objects of the current session. In this blog post I will carry out some tasks with $Error and show you how $Error can help you to troubleshoot and debug your PowerShell code. Let’s jump in.

Assume you are trying to list a folder that doesn’t exist.

Get-ChildItem C:\nothere

We are faced with an error message. This error message will be stored in the $Error Variable.

$Error

But, wait a minute, what kind of error is it?

$error.CategoryInfo

Now let’s clear this error.

$error.Clear()

What about other error categories? Check out this command.

Enter-PSSession -ComputerName NotThere

The reason in this case is an exception of RemoteTransporting.

We can examine the statement that causes the error or exception in more detail.

$Error.InvocationInfo.line

It is worth mentioning that if there are multiple errors in $Error, all errors can be called with square brackets.

Finally, it might be a good idea to store the content of the $Error variable in a file.

$Error | Out-File $home\errors.txt

Open it with Start-Process.

Start-Process $home\errors.txt

At the end I want to show that you can create an error yourself with throw.

throw 'Operation aborted.'

That’s what I wanted to show. See you then!

Categories: PowerShell

Tagged as: ,

1 reply »

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.