Powershell try catch finally
You can intercept any error in try, catch and finally statements.
PowerShell supports try/catch/finally, that should feel familiar to all java, .Net developers.
PowerShell Version 1 introduced the trap statement that still works; I prefer try/catch/finally.
If you are familar with any other programming language, like other programming languages commands
you should execute should be placed in try block.
$error variable should be written in catch block.
Finally as name suggest, you should do the clean up or release the occupied resourses if any.
Example
try {
Remove-Item "C:\doentexist\file.txt" -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
Write-Host "item not found" -ForegroundColor red
}
catch {
Write-Host "undefined errors" -ForegroundColor orange
Write-Host $error[0] -ForegroundColor orange
}
finally {
"Finally block"
}
Copy and Try it