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
}
- SharePoint error - An exception occurred when trying to issue security token: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms..
- PowerShell iterate and get all SharePoint sites and sub sites
- SharePoint Online: Editing session has ended Message
- How to Share Microsoft SharePoint Site with Users or Groups
- How to delete SharePoint Online List Item using REST API
- SharePoint List excel import - This table exceeds the maximum number of supported rows
- How to disable SharePoint subsite creation option for owners
- SharePoint 2010 August 2015 Update KB3055049 - Duplicate Document ID issue bug fixed
- SharePoint Server 2016 Preview installation error - This Product Key isn't a valid Microsoft Office 2016 Product Key. Check that you've entered it correctly.
- How to upload file programmatically to SharePoint Document Library using Server Object Model C# .Net
- Access URL for SharePoint Tenant Admin Center (Online Office 365)
- Error when deleting SharePoint Online folder or file
- How to extend retiring SharePoint 2010 Workflows and continue with Office 365
- How to generate client id and secret to register SharePoint App with OAuth
- How to delete SharePoint List Item programmatically using C#.Net
- How to retrieve all SharePoint Online List Items using Rest API
- [Solved] SharePoint Search Internal server error exception
- Create SharePoint Site Collection using PowerShell New-SPSite
- Fix SharePoint PowerShell error - The term Get-SPweb is not recognized as the name of a cmdlet function script file or operable program
- How to enable anonymous public access for SharePoint Online site collection, file, folder without login ?
- SharePoint Server 2016 installation System Hardware requirements
- How to create SharePoint Online List Item using REST API
- Changed AD user display name showing old name in SharePoint
- Recommended size and resolution for SharePoint Online Site logo
- Microsoft 365: How to Turn Off Delve in SharePoint Online for All Users
- Bash Command to Do Nothing with Example - Bash
- Graph API error when querying BookingBusinesses - ErrorExceededFindCountLimit, The GetBookingMailboxes request returned too many results - Microsoft
- [Vi/Vim] How to move cursor to the start of a line - MacOS
- JavaScript : Get url protocol HTTP, HTTPS, FILE or FTP - JavaScript
- Android: Unknown error code during application install : - Android
- Mac (macos) startup keyboard boot sequence combinations - MacOS
- Fix SharePoint 2019 installation error This product requires Visual C++ Redistributable Package for Visual Studio 2017 - SharePoint
- Increase Font Size of Eclipse Java Code - Eclipse