Posts

Showing posts with the label Catch

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...

Powershell Trapping Get-WMIObject

There are many times when I have to connect to remote servers and get information using WMI but not all of the servers in my list are available all the time... Even though the error from the Get-WMIObject cmdlet is not terminating, I want to handle it. So I use the following code to do it: # Declare the variable to hold the result $servicename # Call the Get-WMIObject cmdlet try     {         $servicename = get - wmiobject win32_service - computername $server - ErrorAction Stop       } catch     {         # If an exception is thrown, set the variable to null         $servicename = $null     }   # Check the value of the variable. if ( - Not ( $servicename - eq $null ) ) {      # Continue processing } else {     # Exception was thrown } ...