使用Get-ADGroup时隐藏错误

Sco*_*ren 13 powershell active-directory

我正在编写一个脚本,如果它不存在,将构建一个新组.我正在使用Get-ADGroup使用以下命令确保该组不存在:

$group = get-adgroup $groupName -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue 
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我收到以下错误(我从错误中删除了任何特定于域的数据):

Get-ADGroup : Cannot find an object with identity: '*group name*' under: '*domain*'.
At U:\Scripts\Windows\Create-FolderAccessGroup.ps1:23 char:24
+ $group = get-adgroup <<<< $groupName -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue
    + CategoryInfo          : ObjectNotFound: (y:ADGroup) [Get-ADGroup], ADIdentityNot
   FoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: '' under: ''.,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
Run Code Online (Sandbox Code Playgroud)

我假设设置ErrorAction和WarningAction为SilentlyContinue将保持此错误显示,但它没有.

小智 19

我发现这个效果最好:

$Group = Get-ADGroup -Filter {SamAccountName -eq $GroupName}
Run Code Online (Sandbox Code Playgroud)

如果过滤器未返回任何结果,则$ Group只会设置为$ null并且不会生成错误消息.此外,由于SAM帐户名在Active Directory中必须是唯一的,因此不存在将$ Group设置为多个对象的数组的风险.

我发现在If语句中检查组(或用户)是否存在时,使用-Filter来获取组而不是-Identity非常有效.例如:

If (Get-ADGroup -Filter {SamAccountName -eq $GroupName})
{
    Add-ADGroupMember -Identity $GroupName -Members $ListOfUserSamAccountNames
}
Else
{
    Write-Warning "Users could not be added to $GroupName because $GroupName
    does not exist in Active Directory."
}
Run Code Online (Sandbox Code Playgroud)

我发现使用带有-Identity参数的Get-ADGroup cmdlet,逻辑上处理(如果组存在,添加用户;如果不存在,则显示消息)比mjolinor建议使用try/catch更容易.考虑使用-Identity参数执行上述操作的try/catch方法:

Try
{
    Get-ADGroup -Identity $GroupName
    Add-ADGroupMember -Identity $GroupName -Members $ListOfUserSamAccountNames
}
Catch
{
    Write-Warning "Users could not be added to $GroupName because $GroupName
    does not exist in Active Directory."
}
Run Code Online (Sandbox Code Playgroud)

您会看到try块中的任何命令是否会引发终止错误.如果有,则意味着该组不存在,并将继续并处理catch块中的命令.它会起作用,但我不认为try/catch在逻辑上与if/else相比也是如此.

不要误会我的意思,mjolinor是PowerShell的天才.只是在这种情况下,我不认为他的解决方案是最好的.


mjo*_*nor 17

 try {get-adgroup <groupname>}
  catch  {
      <make new group>
     }
Run Code Online (Sandbox Code Playgroud)


JPB*_*anc 6

@mjolinor给出了很好的答案,但我认为一些解释也有帮助.

Windows PowerShell提供了两种报告错误的机制:一种用于终止错误的机制和另一种用于非终止错误的机制.

内部CmdLets代码可以ThrowTerminatingError在发生错误时调用方法,该错误不允许或不允许cmdlet继续处理其输入对象.脚本编写者可以使用异常来捕获这些错误.

当cmdlet可以继续处理输入对象时,内部CmdLets代码可以调用WriteError方法来报告非终止错误.然后,脚本编写者可以使用-ErrorAction选项隐藏消息.