Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell 2.0 try catch how to access the exception

People also ask

How do I read an exception in PowerShell?

GetType(). FullName to view the exception message for the last error that occurred. Going back to the PowerShell console, rerun the New-Item command with a non-existent path, then run the $Error command to find the exception message.

How do I get an error code in PowerShell?

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.

Does try catch stop execution PowerShell?

“try” is a PowerShell block that you want PowerShell to monitor for errors. When any error occurs during the script execution, it will immediately stop at that point and move onto the Catch block if the error is a terminating error.

How do you catch non terminating errors in PowerShell?

The above error is generated by cmdlet and it is a non-terminating error. You can handle both the terminating and non-terminating error (by converting them into terminating error) using ErrorAction cmdlet, $ErrorActionPreference variable and try, catch, and finally blocks.


Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.