Exception Handling in PowerShell script

Regular Contributor

Hello Everyone,


To handle the exceptions in PowerShell, Here are the options -


Approach 1


  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




Write-Host 1


} else {


Write-Host 2





Approach 2

  1. 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





    $grpName = "Bhanu Org1 Visitors"

    $grp = Get-PnPGroup -Identity $grpName

    Write-Host "1"




     $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


Thanks & Regards,


0 Replies