2015-02-09 53 views
0

我有一个脚本,它将Active Directory组的成员添加到Office 365通讯组中。 AD组的许多成员也将是通讯组已,这将导致脚本显示错误的成员:抑制Office365中的异常powershell

Adding [email protected] to distribution group GROUP 
The recipient "[email protected]" is already a member of the group "GROUP". 
+ CategoryInfo   : NotSpecified: ([email protected]: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并捕获所有错误并编写“错误!”而不是实际的例外,但是这似乎没有生效。

目前,我的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" 
    } 
} 

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

+1

这可能不是一个终止错误。如果将-ErrorAction Stop添加到Add-DitributionGroupMember cmdlet,它会起作用吗? – mjolinor 2015-02-09 13:13:14

回答

0

感谢@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 [email protected] to distribution group GROUP 
[email protected] is already a member of GROUP. 
+0

遇到同样的问题。并且您不得不将异常类型添加到Catch中的提示不适用于我。简单的Catch也不适合我。你使用的是什么版本的Powershell?我在5.0.10586.63。谢谢。 – 2016-02-09 20:26:45

+0

'$ PSVersionTable'表明我正在使用5.0.10240.16384。 – 2016-02-10 23:19:58