Updates
recent

Error Handling Tips in PowerShell

Hi Geeks, We all know the ways to handle error in scripting or programming languages i.e Try, Catch, Finally and so on. The same thing can also be done in PowerShell.

Example :

Try { $a = 1/0 } Catch { Write-Host “Got Exception” }




But suppose your script is too long and you want your Error should be handled in such a way that you can know exactly what caused the error and at which path or line number. So to do so PowerShell provides some cool properties as given below :

To Catch the Complete Exception -> $_.Exception

To Find the exact Error Line number -> $_.InvocationInfo.ScriptLineNumber

To only get the Exception Message -> $_.Exception.Message

So will look like this :

Try
         Your Script Goes here 
}
Catch
{
        $Exception = $_.Exception
        $Line = $_.InvocationInfo.ScriptLineNumber
        $Message = $Exception.Message
}

FINAL OUTPUT :




                                 
                          Hope you all enjoyed the Tutorial. Do like and Share for more.




Copyright © 2016 Amar Helloween. Powered by Blogger.