在 Office365 powershell 中抑制异常

Suppress Exception in Office365 powershell

我有一个脚本可以将 Active Directory 组的成员添加到 Office 365 通讯组。 AD 组的许多成员也已经是通讯组的成员,这导致脚本显示错误:

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

我想抑制这些错误,因为我不关心成员是否已经存在。

我已经尝试捕获 MemberAlreadyExistsException,设置 -ErrorAction SilentlyContinue 并捕获所有错误并写入 "Error!" 而不是实际的异常,但这似乎没有生效。

目前,我的 Try-Catch 块如下所示:

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"
    }
}

我相信当用户已经存在时这应该提醒我,但是我仍然收到一条异常消息。

感谢@mjolinor,我能够捕获异常并提供更加用户友好的消息。我更正后的代码如下:

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"
    }
}

我按照建议添加了 -ErrorAction Stop,这允许我 Catch 例外。我还修改了异常类型以捕获所有异常。有趣的是(在我看来),如果我没有在其中放置异常类型,Catch 块就会失败。

程序输出现在是:

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