Exception handling in PowerShell

Microsoft TechnologiesSoftware & CodingPowerShell

In this article, we will go through the below points.

  • What is an Exception in PowerShell?

  • Terminating and Non-Terminating errors.

  • Using Try / Catch block.

  • Converting Non-Terminating error to Terminating Errors.

  • Handling actual exception messages.

What is the exception in PowerShell?

Exception in PowerShell or other programming languages is the error or unexpected result that can be handled. For example, File not found while executing, dividing a number by zero.

The exception can stop script execution if not handled properly.

Terminating Errors and Non-Terminating Errors

  • Non-Terminating errors don't halt script execution and it continuously runs script even if it is detected in the script. Below is an example of the non-terminating errors.

Example 1

if(Get-Service -Name DoesntExist) {
   Write-Output "Service Found"
}else {
   Write-Output "Service not found"
}
Write-Output "This Line will be printed"

Output

           As you see the Write-Output is printed even if the service name is not found. So the script execution continues.

  • Terminating errors stop the script executions if found and is considered a serious issue if your program is not designed to handle this type of error sometimes they are useful when we need to terminate the script if something goes wrong.

    The “Throw” command terminates the script.

Example 2

if(Get-Service -Name DoesntExist) {
   Write-Output "Service Found"
}else {
   throw "Service not found"
}
Write-Output "This Line will be printed"

Output

And as you can see, write-output is not printed because of the “throw” command it terminates.

Using Try/Catch block to handle the exception

Let’s write this code inside the try/catch block which is popular in programming languages for exception handling.

Example 3

try {
   if(Get-Service -Name DoesntExist) {
      Write-Output "Service Found"
   }else {
      Write-Output "Service not found"
   }
   Write-Output "This Line will be printed"
}catch {
   Write-Output "Error Occured"
}

Output

Same Output as the example1 and here there is no use of using try/catch block. We will make some changes in the script to make try/catch block useful in an easier way in a few mins.

Let’s convert example2 into a try/catch block.

Example 4

try {
   if(Get-Service -Name DoesntExist) {
      Write-Output "Service Found"
   }else {
      throw "Service not found"
   }
   Write-Output "This Line will be printed"
}catch {
   Write-Output "Error Occured"
}

Output

So throw command terminates the scripts and moves to the catch block and the exception output is displayed. However, we are still getting the error message (in red) and the catch output is displayed later.

Convert the Non-Terminating error to the terminating error

A better way to handle this exception is to convert the non-terminating error to the terminating one using the ErrorAction parameter or $ErrorActionPreference variable. By default, the value for this variable is set to the Continue by PowerShell so in the case of error, the program continues. If we set this variable or parameter value to “Stop” and if an error occurs by the cmdlet then it terminates the script in the try block and continues execution in the catch block.

Example 5

try {
   if(Get-Service -Name DoesntExist -ErrorAction Stop) {
      Write-Output "Service Found"
   }else {
      Write-Output "Service not found"
   }
   Write-Output "This Line will be printed"
}catch {
   Write-Host "Error Occured" -f Red
}

Output

Error Occured

As you see it only displays the catch block because the service doesn’t exist. Let’s use the $ErrorActionPreference variable it is an alternate to -ErrorAction parameter but it is applicable throughout the script.

Example 6

$ErrorActionPreference = "Stop"
try {
   if(Get-Service -Name DoesntExist) {
      Write-Output "Service Found"
   }
}catch {
   Write-Host "Error Occured" -f Red
}

The output will be the same as above.

Handling Actual error messages

Instead of writing the custom error messages, you can also directly capture the error message produced by the cmdlet as shown below.

Example 7

$ErrorActionPreference = "Stop"
try {
   if(Get-Service -Name DoesntExist) {
      Write-Output "Service Found"
   }
}catch {
   $_.Exception
}

Output

raja
Updated on 18-Feb-2022 06:50:00

Advertisements