2015-02-09 74 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