EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Try-catch in PowerShell
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Try-catch in PowerShell

By Priya PedamkarPriya Pedamkar

Try - catch in PowerShell

Introduction to Try-catch in PowerShell

A good practice while working on any script or program is to have a mechanism for error handling. Though it may take a little bit of additional time, its rewards are priceless. Try-catch in PowerShell in this article, it is not possible for any script or program to run without any error or issue 100% of the time. It is not necessary that an error always must occur because of logical errors in the script. Many external factors may also affect the successful running of the script. To avoid these kinds of surprises, it is better to implement the error handling mechanism.

There are two types of errors that can be occurring during script execution. They are terminating and non-terminating errors. As the name implies, terminating error will stop the program from further execution, whereas a non-terminating error will not stop the execution. An example of terminating error would be a syntax error whereas an example of non-terminating error would be missing a file.

Understanding Try-Catch

In PowerShell, the error handling is done through trial and catch blocks. The try block will have the code, that may likely throw an error. The catch block contains the code or action to be executed in case of an error that is thrown by the try block. Additionally, a final block can be used to free up the resources. Mostly, non-terminating errors can’t be handled in PowerShell. To handle such errors, they needed to be specifically converted to as a terminating error. This can be done using ErrorActionPreference.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The general syntax of the try-catch block is as follows

Try
{
//code1 that may generate exception
//code2 that may generate exception
//code3 that may generate exception
//to catch non-terminating error, convert them to terminating error
}
Catch(error)
{
//code to be executed
//multiple catch blocks can be included, or the same catch block can be used to catch multiple exceptions
// the error information is present inside the $_ variable
//The error can be logged to a text file or can trigger an email to inform some user about the error
}
Finally
{
//code to be executed
//this is an optional block of code
}

The syntax for Multiple Catch:

try
{
//code to be executed
}
catch [System.IO.DirectoryNotFoundException] {
Write-Output "Directory Not Exception"
}
catch [System.IO.IOException] {
Write-Output "Input/output Exception"
}
catch [System.IO.FileNotFoundException] {
Write-Output "File Not Found Exception"
}

Parameters

Setting the Error action parameter can be done in many ways. The following are the possible values for the ErrorAction parameter.

  • If -ErrorAction Stop: It throws the error and stops the execution of the program.
  • If -ErrorAction Inquire/Continue: Throws error but continues with the execution of the program.
  • If -ErrorAction SilentlyContinue: Error is not thrown, and the execution continues
  • If – ErrorAction Ignore: Error is not thrown, and the execution continues

The difference between silently continue and ignore is that silently stores the error details in the $error variable whereas ignore doesn’t do that.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)

Examples of Try-catch in PowerShell

The below is a sample usage of Try, catch block:

Code:

try
{
dfdgfdfgf
sfsdf
dsfdfdsf
}
catch
{
write-host "Exception caught"
}

Output:

Try-catch in PowerShell

Example #1

Various parameters of ErrorActionPreference.

Code:

Write-Host "Example Error Action Preference: stop"
$ErrorActionPreference = 'Stop'
$test= 9/0
Write-Host "Still running"

Output:

Try-catch in PowerShell

Try-catch in PowerShell

As you can see, the execution is stopped immediately after an error has occurred.

Let’s change it to continue

Code:

Write-Host " Demo"
$ErrorActionPreference = 'Continue'
$test= 9/0
Write-Host "Still running"

Output:

try catch in powdershell

If you see in the above output, “Still running” is printed even after the occurrence of error

Let’s see the same input with ErrorActionSet set as ‘Silently continue’

Code:

Write-Host " Sample test"
$ErrorActionPreference = 'SilentlyContinue'
$test= 9/0
Write-Host "Still running"

Output:

try catch in powdershell

As you can see, none of the errors are displayed on the screen and the execution is continued.

Example #2

Writing Error Message to Console.

Code:

Try {
Get-ThisWontWorktestcommand
}
Catch  {
Write-Host "The command ran is not found"`n -ForegroundColor Blue
Write-Host "Message: [$($_.Exception.Message)"] -ForegroundColor Red -BackgroundColor DarkBlue
}

Output:

try catch in powdershell

Error Handling Best Practices

  • If there is an exception that sits across your face, try to find a solution to avoid that completely instead of going for exception handling.
  • Check the functionality of the code in case if the same error occurs frequently.
  • Try to catch the specific type of exception that is trying block is going to return, in case of not knowing the type of exception that is going to occur create a generic catch block.
  • Better to capture the exception message in an output file along with a timestamp and exception message.
  • It is advisable not to create an empty catch block.

Conclusion

Thus, the article covered in detail about the try block feature in PowerShell. For any person aspiring to be a good developer in PowerShell, it is important that they have a very strong understanding of the error handling mechanism. In the case of automated jobs, without error handling mechanisms implemented in the code, it will be a nightmare for the administrator to understand what the issue is or when an issue has occurred.

Recommended Articles

This is a guide to Try-catch in PowerShell. Here we discuss the Understanding of Try-Catch, Error handling best practices along with the examples. You may also look at the following articles to learn more –

  1. Loops in PowerShell
  2. PowerShell Environment Variables
  3. How to Format the Table in Powershell?
  4. Guide to 7 Different PowerShell Tools
Popular Course in this category
All in One Data Science Bundle (360+ Courses, 50+ projects)
  360+ Online Courses |  1500+ Hours |  Verifiable Certificates |  Lifetime Access
4.7
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
Data Visualization Training (15 Courses, 5+ Projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more