无法在Powershell脚本中捕获ADException

时间:2013-10-01 18:59:02

标签: powershell exception-handling active-directory

我正在使用ActiveDirectory Powershell模块将一些组添加到我们的域中。在此过程中,脚本可能会尝试将用户添加到他们已经是其成员的组中。这是我应该能够处理的一个例外,但是,我似乎无法抓住它。无论我做什么,我都会在powershell控制台中看到红色文字。

我将这一切简化为几个可测试的步骤。

New-ADGroup -Path "ou=temp,dc=domain,dc=tld" -GroupScope Global -Identity testGroup
Get-ADGroup -Identity testGroup | Add-ADGroupMember -Members testUser
try
{
    Get-ADGroup -Identity testGroup | Add-ADGroupMember -Members testUser
}
catch
{
    Write-Warning "Caught exception!"
}

我希望看到“抓到异常!”但是,在黄色文本中,我实际得到的是:

Add-ADGroupMember : The specified account name is already a member of the group At line:1 char:40
+ try {Get-ADGroup -Identity testGroup | Add-ADGroupMember -Members testUser} ca ...
+                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (CN=testGroup,OU=Temp,DC=domain,DC=tld:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

全部为红色文字。

我希望我忽略了一些简单的事情。我很感激任何意见。

编辑:请求的PS版本信息:

C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      3.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.18331
BuildVersion                   6.2.9200.16481
PSCompatibleVersions           {1.0, 2.0, 3.0}
PSRemotingProtocolVersion      2.2

2 个答案:

答案 0 :(得分:3)

Add-ADGroupMember支持常见的cmdlet参数。我会尝试添加-ErrorAction Stop,看看是否允许它被捕获。例如,这适用于其他cmdlet,如Get-Content

try { gc "NotAFile.txt" } catch { write-warning $_ }

会写错误,但

try { gc "NotAFile.txt" -ErrorAction Stop } catch { write-warning $_ }

写下警告。

答案 1 :(得分:2)

你确定那里还有别的东西吗?它对我来说很好用:

PS H:\> try { Add-ADGroupMember -Identity "testgroup" -members (get-adcomputer MyComputerName) } catch {Write-Warning "$_"}
WARNING: The specified account name is already a member of the group