In v1.0 of Windows Powershell, there was no Try-Catch-Finally feature. We had trap construct for the same purpose. I think, Trap was a new concept as it was not there in any of the existing .NET-based languages. But Powershell v1.0 somehow had this unusual feature. In most of the old machines, there will be Powershell v1.0 and we cannot use Try-Catch blocks for those servers. So if you are writing script for all versions of Windows, there is no option left except using Trap.
Let us see the Trap example below :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#---------------------------------------------------------------------------------------------------- | |
#-- Try catch Demo | |
#---------------------------------------------------------------------------------------------------- | |
cls | |
#--Script Level Error Capturing --# | |
Trap { | |
echo "Top block:" | |
echo "Failed with error : $($Error[0].Exception.Message) " | |
return | |
} | |
function divide-numbers([int]$x , [int]$y) | |
{ | |
#--Function Level Error Capturing --# | |
Trap { | |
echo "Function block:" | |
echo "Failed with error : $($Error[0].Exception.Message) " | |
echo "Error Occured while dividing $x with $y" | |
return | |
} | |
$z= $x/$y | |
echo $z | |
} | |
divide-numbers 15 0 | |
$x=9 | |
$z= $x/0 | |
#---------------------------------------------------------------------------------------------------- |
The above example will call two divide statement which will end up with divide-by-zero. There are two blocks where trap is declared :
1. At script level
2. At function level
You will notice that output will call Function level when it will fail inside function block and it will call script level trap when called outside function.
Hope this simple example will make you learn this correctly. Please send me your questions and suggestion if you have any. Learning from small example is always better if you want to understand something correctly.
That's it for today! Thanks for reading today and keep reading this blog which is updated everyday.
No comments:
Post a Comment