Recently I had a project to develop a web portal that would trigger a powerCLI script. The problem was that if anything except the required JSON output popped up, especially any errors, the whole thing would crash. The only work around was to error handle the sh#t out of the code!!!
The best and easiest way to error handle / catch exceptions is to use try / catch blocks – if you’re familiar with Java (or any kind of) programming, powershell try catch blocks work exactly the same way. If you’re not – don’t worry I got your back.
What is a try catch block?
Try catch block is a way to structure your code to handle errors and catch any exceptions that your code might throw. There is also a “Finally” block that is also a part of the whole thing.
Try block – This is where you place the code which you need to check for exceptions
Catch block – This is where you specify what you need the code to do IF an exception is caught
Finally block – This is where you specify the code that you need to run regardless of whether an exception was caught or not
try{
//The code that needs checking for exceptions
}
catch{
//What should happen if an exception is caught
}
Finally{
//What should run regardless of what happens above
}
Code Example
try{
Connect-VIServer $vcenter -Credential $credentials -ErrorAction Stop
Write-host "This will not run if an exception is caught"
}
catch{
Write-host "Oops something is wrong with the credentials"
}
Finally{
Write-host "This runs regardless of what happens above"
}
The above code is a PowerCLI script which will try to connect to a vCenter with the given credentials and if an exception is caught it will display the text in the catch block.
IMPORTANT: DONT FORGET THE -ERRORACTION The -ErrorAction stop is extremely important for the code to function as expected. This is will stop powershell from executing the next lines and divert the code to the catch block. If ErrorAction was not there it will continue executing everything regardless of an exception.