If you are a programmer, you certainly use exception handling logic in your code or script, which is a best practice while coding. Exceptions may break your code and its necessary to catch and handle errors for a smoother execution in case something goes wrong. Identify what is wrong and ensure it does not break the code execution.
PowerShell too provides option to use try-catch blocks similar to other programming languages like .Net, Java.
Though the below examples are related to SharePoint Online, the approach remains same for any PowerShell script. You may even use try-catch with CSOM (Client Side Object Model), PnP.
Assumption - You already know basic commands of SharePoint Online Management Shell / Window ISE PowerShell to establish a connection with Microsoft Office 365 SharePoint Online Site Collection. Ensure you "Run as Administrator".
PowerShell Example - Basic Try-Catch block
try {
Connect-SPOService -Url "https://code2care.sharepoint.com/sites/PowerShell"
}
catch {
"There was an error connecting to the SharePoint site"
}
PowerShell Example - Catch multiple errors
try {
//Script
}
catch [Exception 1],[Exception 2] {
"Friendly error message"
}
catch {
"Generic error message"
}
Within a Catch block, the current error exception information can be accessed using $_, which is also known as $PSItem. The object is of type ErrorRecord.
PowerShell Example - Access information of current exception
try {
//Script
}
catch {
Write-Host "There was an error, error details below"
Write-Host $_ //This will print the error details
}
Additional properties that can be accessed related to the exception.
ScriptStackTrace
Exception
ErrorDetails
PowerShell Example - Print exact exception message
Example - You can use $_.Exception.Message to print the exact exception messagetry {
Connect-SPOService -Url "https://code2care.sharepoint.com/sites/PowerShell"
}
catch {
Write-host "There was an error - " $_.Exception.Message
}
This will print a message - There was an error - Could not connect to SharePoint Online.
⚡️ Terminating and Non Terminating errors
Exceptions are classified into 2 types -- Terminating error - halt/pause the function or operation
- Non-Terminating error - allow to continue further execution
PowerShell Example - Use 'ErrorAction' parameter to catch non-terminating error
Add '-ErrorAction Stop' at the end of cmdlet.try {
Connect-SPOService -Url "https://code2care.sharepoint.com/sites/PowerShell" -ErrorAction Stop
}
catch {
Write-host "Looks like the SharePoint site does not exist, please re-check."
}
PowerShell Example - Use '$ErrorActionPreference' variable to catch non-terminating error
Add '-ErrorAction Stop' at the end of cmdlet. Set '$ErrorActionPreference = "Stop"' to make errors as terminating, and set it back to "Continue" in Finally block.try {
$ErrorActionPreference = "Stop"
Connect-SPOService -Url "https://code2care.sharepoint.com/sites/PowerShell" -ErrorAction Stop
}
catch {
Write-host "Looks like the SharePoint site does not exist, please verify."
}
finally {
$ErrorActionPreference = "Continue"
}
We have used 2 actions for $ErrorActionPreference variable here (Stop and Continue), but it supports below values which tells what action to take for the error.
- Continue (default action) - Display/Print error message and continue execution of further commands.
- Stop - Terminate action with error.
- SilentlyContinue - Do not display error message and continue.
- Break - Debug error/exception to troubleshoot what went wrong.
- Inquire - Ask user whether to terminate or or continue.
- Ignore - Suppresses error and continue. Not recommended.
PowerShell Example - Use Finally block
This block runs always, irrespective of whether there was error or not. Use this section to perform action which should execute whether there was an error or not.try {
Connect-SPOService -Url "https://code2care.sharepoint.com/sites/PowerShell" -ErrorAction Stop
}
catch {
Write-host "Custom message."
}
finally {
//Write something which you want to execute always
}
- error CAML Query containing special characters
- [Solved] SharePoint Illegal operation attempted on a registry key that has been marked for deletion
- Trigger Flow on selected Listitem from SharePoint view - create button with JSON column formatting
- SharePoint Excel error - The workbook cannot be opened because it contains the following features that are not supported by Excel in the browser
- Send Email with attachment using SharePoint PowerShell, SMTP server
- How to show or hide columns in SharePoint Online List Library from
- SharePoint excel error - A problem occurred while connecting to the server. If the problem continues, contact your administrator.
- How to get SharePoint Online user details from person or group column using REST API
- How to get SharePoint List Item URL using PowerShell
- How to get the SharePoint Tenant Login URL
- Special character & not working with SharePoint REST API
- How to disable SharePoint subsite creation option for owners
- Managed Metadata error - The data returned from the tagging UI was not formatted correctly
- Deploy SharePoint wsp solution package using PowerShell
- How to create classic site in SharePoint Online
- See actual SharePoint error exception modify web.config
- 'Edit Document' Requires a Windows Sharepoint Services-compatible application and Microsoft Internet Explorer 6.0 or higher
- How to enable anonymous public access for SharePoint Online site collection, file, folder without login ?
- SharePoint installation error - Setup is unable to proceed due to the following error This product requires Microsoft .Net Framework 4.5
- How to add animated Gif to SharePoint Online Page
- [Solved] SharePoint Search Internal server error exception
- How to create SharePoint Document Library
- SharePoint - Use Today's Date Time in list view filter and calculated column
- How to redirect SharePoint Site Collection to different URL
- SharePoint error cannot connect to the configuration database
- Ways to Convert Integer or int to Long in Java - Java
- StringJoiner Example with Java Collections - Java
- How to install Python 2.7.xx on macOS 12.3 Monterey or higher - Python
- Drop table using Java JDBC Template - Java
- Iterate over an Array using Java 8 Stream and foreach - Java
- Fahrenheit to Celsius Temperature Convertor: Tool & Formula - Tools
- How to update all installed packages at once in Ubuntu - Ubuntu
- How to install Android Studio Chipmunk and SDK tools on macOS (2021.2) - Android-Studio