$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!
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