Posts

Showing posts with the label Finally

Catching Exceptions in PowerShell

Things can go wrong even on the simplest tasks. A network failure, a fail over, inadequate permissions and many other factors can make your scripts and functions fail. Let's see how we can control failure! There are two statements in PowerShell that help to control failed commands. These are "try" and "catch". Their usage is pretty straightforward, you wrap the commands that might fail in a try block and specify the actions to be executed upon the failure in the catch block. Below is a simple try/catch block in a function: try { Remove-Item -Path myfile.txt -ErrorAction Stop } catch { Write-Host "Cound not remove item" } Here, if the Remove-Item command fails, the string "Could not remove item" will be written on the console. A couple of things to notice here. First, the -ErrorAction preference is set to Stop for the command since this way the command will generate and exception instead of just writing to the error s...