Saturday, April 18, 2015

#53 : Error Handling with $Error

$Error is an interesting array which records all error messages from current session. It can be cleared also and looked up for presence of any error message in last command. In most of the cases, you may want to set it clear and then look for $error[0].

Make sure when you check the $error.count right after you run the statement which you think as problematic statement.

Code:

$error.clear()

copy-item “c:\temp\abc.txt” “d:\abc.txt”

if ( $error.count -ne 0 )

{

echo “An error occurred in copy operation. Please review the message below:”

echo $error[0]

}

When you run the above in console and abc.txt does not exist, you will get an error message in red color and then from echo part as well. You might be thinking why we need this if error message is there in console. The reason behind using is that if you run the script from a scheduler and want output to be there in log file, this approach can help you a lot.

Other better methods of catching exceptions are:

Try.. Catch

Trap

We will discuss about them in next article. Test this approach and let know your responses.

Enjoy!

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...