• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Stephanos Constantinou Blog

PowerShell Scripting

  • Home
  • Blogs
    • PowerShell Tutorials
    • PowerShell Scripts
    • PowerShell Modules
      • Modules Cmdlets
    • Software Reviews
  • About
  • Contact
You are here: Home / PowerShell Tutorials / PowerShell Try Catch Finally

PowerShell Try Catch Finally

01/08/2018 by Stephanos 6 Comments

PowerShell Try Catch Finally

In this tutorial we will see about PowerShell Try Catch Finally. We will see what it does and some example on how we are able to use it. It is used to handle and respond to terminating errors. When a terminating error occurs, Windows PowerShell will stop running a script or function if there is no error handling. Try Catch Finally consisted by three blocks where statements exist in them.

Try

Try block is used to monitor the statements within, for any errors. If a terminating error will occur on any of the statements in Try block, Windows PowerShell will try to find a Catch block or Trap that matches the specific error in order to respond. The error is saved in $Error variable by default. If no Catch block or Trap is found for error handling, Finally block will run and then the error will be written to the error stream.

Syntax:

try {<statement list>}

 

[adinserter name=”In Article”]

Catch

If there is a Catch block to handle the error, then the statements within the Catch block will run. You can define which errors to be handled by a Catch block. You are allowed to have multiple Catch blocks, so you are able to handle each error a differently. You are allowed to not include any Catch statement in a Try statement. Instead of a Catch block you can use Trap to handle errors.

Syntax:

catch [[<error type>][',' <error type>]*] {<statement list>}

 

If you would like to know which error types are loaded on your system, in order to specify which errors to be handled by each Catch block, you need to run the below code.

Code:

([appdomain]::CurrentDomain.GetAssemblies() |
    Where-Object {$_.Location -ne $null} |
        foreach {$_.GetExportedTypes() |
            Where-Object {$_.Fullname -match 'Exception'}}).FullName

 

Output:

PowerShell Try Catch Finally - Error Types

 

The above code will provide you with the full name of all exceptions loaded in your system. When I run it on my system it gave me 341 error types. This depends on what you have loaded.

If you want to refer to the error, within the Catch block, you are able to use $_ or $PSItem. There are also methods to use for re-throwing an error such as:

  • Write-Error
  • $PSCmdlet.WriteError()
  • Throw
  • $PSCmdlet.ThrowTerminatingError() 

I am not going into more details about this now. A separate post will be at a later stage only related to errors. I really good post from Kevin Marquette on his blog will give you more information for now. You can find it here.

https://kevinmarquette.github.io/2017-04-10-Powershell-exceptions-everything-you-ever-wanted-to-know/#write-error–erroraction-stop

 

[adinserter name=”In Article”]

Finally

Catch block is followed by Finally block. Finally block is used to free any resources that are no longer needed by your script, as mentioned in Microsoft. Finally block will run before terminating a script or block. It will run even if you hit CTRL+C or use Exit keyword in Catch block. As CTRL+C terminates the pipeline, if you have anything to display on the screen in Finally block it will not be shown, although the Finally block will run.

Syntax:

finally {<statement list>}

 

Now lets see few examples on how we are able to use Try Catch Finally to help you understand better.

 

Example 1

In this example we are using only one Catch block along with the try statement. The Catch block in this case, as we have not defined any specific error to handle, it will handle all type of error that might occur in Try block. In the first part the command is correct so we are not receiving any error and the date is displayed. At the second part where the command is wrong, instead of getting the current date or the error that the command does not exist, we will get the output from Catch block.

Code:

try{Get-Date}
catch{"There is an error in Try block"}
try{Get-Dates}
catch{"There is an error in Try block"}

Output:

PowerShell Try Catch Finally - Example 1

 

[adinserter name=”In Article”]

Example 2

In this example we will user two Catch blocks in the same Try statement. The first Catch block will be used in case of “Command not found” error only. In there is such error it will display on the screen “There is no such command”. For all other errors, the second Catch block will run and it will display “There is an error in Try block” on the screen. In the first part we are using a command that does not exists so the first catch block will run. At the second part the parameter is used incorrectly. In this case the error is different and the second catch block will run.

Code:

try{Get-Dates}
catch [System.Management.Automation.CommandNotFoundException]
{"There is no such command"}
catch{"There is an error in Try block"}
try{Get-Date -Date}
catch [System.Management.Automation.CommandNotFoundException]
{"There is no such command"}
catch{"There is an error in Try block"}

Output:

PowerShell Try Catch Finally - Example 2

 

[adinserter name=”In Article”]

Example 3

In this example we will use also a finally block.

Code:

try{Get-Date}
catch{"There is an error in Try block"}
finally{"Finally block is running"}
try{Get-Dates}
catch [System.Management.Automation.CommandNotFoundException]
{"There is no such command"}
catch{"There is an error in Try block"}
finally{"Finally block is running"}
try{Get-Date -Date}
catch [System.Management.Automation.CommandNotFoundException]
{"There is no such command"}
catch{"There is an error in Try block"}
finally{"Finally block is running"}

Output:

PowerShell Try Catch Finally - Example 3

 

I hope the tutorial about PowerShell Try Catch Finally is helpful.

Please let me know your comments and thoughts.

You feedback is appreciated.

[adinserter name=”In Article”]

Related Links:

  • PowerShell Tutorials
  • PowerShell Scripts
  • about_Try_Catch_Finally | Microsoft Docs
  • Get-Date – Microsoft Docs
  • Write-Error – Microsoft Docs
  • about_Throw | Microsoft Docs
  • Where-Object – Microsoft Docs
  • about_Foreach | Microsoft Docs
  • PowerShell Comparison Operators

[adinserter name=”Matched-Content”]

Summary
PowerShell Try Catch Finally
Article Name
PowerShell Try Catch Finally
Description
PowerShell Try Catch Finally. In this tutorial you will find information about PowerShell Try Catch Finally and their use. Stephanos Constantinou Blog
Author
Stephanos
Publisher Name
Stephanos Constantinou Blog
Publisher Logo
Stephanos Constantinou Blog

Filed Under: PowerShell Tutorials Tagged With: Comparison Operators, Get-Date, PowerShell ForEach, PowerShell Operators, PowerShell Throw, Where-Object, Write-Error

Reader Interactions

Comments

  1. Josh says

    02/08/2018 at 08:50

    Hey Stephanos

    Doesn’t this article contradict itself?

    You state the following in the description of Finally.
    “if you have anything to display on the screen in Finally block it will not be shown, although the Finally block will run.”

    Then in your example I can clearly see that it puts an output.

    Best regards
    Josh

    Reply
    • Stephanos says

      02/08/2018 at 09:07

      Hello Josh,

      Thank you for your comment. You need to take the whole sentence, not just part of it as it changes the meaning. what you mentioned above happens only when you hit CTRL+C to stop the script. Please check again that point to help you understand. In my example I have not stopped it.

      If you have any other question let me know.

      Thanks
      Stephanos

      Reply
  2. Dirk says

    02/08/2018 at 14:27

    Hi Stephanos,
    nice post, thanks a lot for sharing.
    I often find myself using try/catch during the development of a script as a poor man’s conditional breakpoint and troubleshooting aid. I just surround the statement(s), that I suspect to be the culprit, in a try block and set a breakpoint within the catch block.
    Thanks again,
    Dirk

    Reply
    • Stephanos says

      02/08/2018 at 15:19

      Hi Dirk,

      Thank you for your feedback. I hope that you will like my future posts

      Thanks
      Stephanos

      Reply
  3. Brian says

    02/08/2018 at 20:19

    Thanks for this post. I’ve read a few articles while trying to learn try/catch and this one explains it the best! I didn’t know about Finally either. Great breakdowns and examples.

    Reply
  4. Stephanos says

    02/08/2018 at 22:10

    Dear Brian,

    Thank you for your comments. I hope my next posts will help you too.

    Thanks
    Stephanos

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Footer

Recent Posts

  • ICS Cube Product Review 26/04/2019
  • PowerShell Module SysInfo v1.2.0 15/03/2019
  • PowerShell Module SysInfo v1.1.2 13/11/2018
  • PowerShell Module SysInfo 24/10/2018
  • Get-VoltageProbe 24/10/2018
  • Get-VideoController 24/10/2018
  • Get-USBController 24/10/2018
  • Get-TrackPoint 24/10/2018
  • Get-TrackBall 24/10/2018
  • Get-TouchScreen 24/10/2018
Planet PowerShell

Categories

  • Modules Cmdlets (57)
  • PowerShell Modules (5)
  • PowerShell Scripts (38)
  • PowerShell Tutorials (35)
  • Software Reviews (2)

Archives

  • April 2019 (1)
  • March 2019 (1)
  • November 2018 (1)
  • October 2018 (56)
  • September 2018 (13)
  • August 2018 (9)
  • July 2018 (6)
  • June 2018 (8)
  • May 2018 (7)
  • April 2018 (9)
  • March 2018 (4)
  • February 2018 (6)
  • January 2018 (12)
  • December 2017 (4)
Top 10 PowerShell 2018

Blogroll

  • Planet PowerShell
  • Reddit – PowerShell
  • PowerShell Magazine
  • PowerShell.org
  • PowerShell Team Blog
  • Hey, Scripting Guy! Blog
  • Mike F Robbins
  • PowerShell Explained with Kevin Marquette
  • Mike Kanakos – Network Admin
  • The Lonely Administrator
  • AskME4Tech
PowerShell Blogs Sysadmin Blogs Banners for Top 20 Programming Blogs

© 2023 · Stephanos Constantinou Blog

  • Home
  • Blogs
  • About
  • Contact