Forum Discussion
Exception Handling in PowerShell script
Hello Everyone,
To handle the exceptions in PowerShell, Here are the options -
Approach 1
- Append the PS Statement with -ErrorAction SilentlyContinue
$grp = Get-PnPGroup -Identity 'Bhanu Org1 Visitors' -ErrorAction SilentlyContinue
2. If any exception is there in above statement also, it will not be prompted. But, in the next step, we need to put a verification as below
if($grp){
Write-Host 1
} else {
Write-Host 2
}
Approach 2
- Have the below statement in the beginning of the script execution
$ErrorActionPreference = "Stop"
2. And then the statements that you think might have chance to break – put it in the Try & Catch block as below
try
{
$grpName = "Bhanu Org1 Visitors"
$grp = Get-PnPGroup -Identity $grpName
Write-Host "1"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage
}
Write-Host "3"
3. In the above script, group name with the given value do not exist and am trying to get the group instance
4. So, the control will go into the catch block and print the value “Group cannot be found”
5. And then, value 3 will be written on the console
Please share your thoughts if you have any better suggestions.
Thanks for the below reference articles
- https://www.sharepointpals.com/post/how-to-use-try-catch-finally-and-error-handling-in-powershell/
- https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters?view=powershell-6
Thanks & Regards,
Bhanu