简体   繁体   中英

Suppress Exception in Office365 powershell

I have a script which adds members of an Active Directory group to an Office 365 distribution group. Many members of the AD group will also be members of the distribution group already, which causes the script to display the error:

Adding user@domain.com to distribution group GROUP
The recipient "user@domain.com" is already a member of the group "GROUP".
+ CategoryInfo          : NotSpecified: (user@domain.com:RecipientWithAdUserGroupIdParameter`1)
[Add-DistributionGroupMember], MemberAlreadyExistsException
+ FullyQualifiedErrorId : [Server=HKNPR04MB0531,RequestId=84dc77fb-8cf4-4e2f-882e-0ce66b735d08,TimeStamp=9/02/2015 6:55:13 AM] [FailureCategory=Cmdlet-MemberAlreadyExistsException] 7CEFF683,Microsoft.Exchange.Management.RecipientTasks.AddDistributionGroupMember
+ PSComputerName        : pod51055psh.outlook.com

I would like to suppress these errors, as I don't care if the members already exist.

I have tried catching the MemberAlreadyExistsException , setting -ErrorAction SilentlyContinue and catching all errors and writing "Error!" instead of the actual exception, however this does not seem to have taken effect.

Currently, my Try-Catch block looks like this:

try 
{
    Add-DistributionGroupMember -Identity $DistributionGroupName -Member $MemberEmail
}
Catch [System.Management.Automation.RemoteException]
{
    if($_.FullyQualifiedErrorId -match 'AlreadyExists')
    {
        Write-Output "`t   $emailaddress is already a member of $DistributionGroupName."
    }
    else
    {
        Write-Output "`t $_.Exception"
    }
}

I believe that this should alert me when a user already exists, however I still receive an exception message.

Thanks to @mjolinor, I was able to catch the exception and provide a more user-friendly message. My corrected code is below:

try 
{
    Add-DistributionGroupMember -Identity $DistributionGroupName -Member $EmailAddress -ErrorAction Stop
}
Catch [System.Exception]
{
    if($_.FullyQualifiedErrorId -match 'AlreadyExists')
    {
        Write-Output "`t   $emailaddress is already a member of $DistributionGroupName."
    }
    else
    {
        Write-Output "`t $_.Exception"
    }
}

I added the -ErrorAction Stop as suggested, which allowed me to Catch the exception. I also modified the exception type to catch all exceptions. Interestingly (in my opinion), the Catch block failed if I did not put an exception type in there.

Program output is now:

Adding user@domain.com to distribution group GROUP
user@domain.com is already a member of GROUP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM