我正在编写一个脚本,如果新组不存在,它将构建一个新组。我使用以下命令使用Get-ADGroup来确保该组不存在:
$group = get-adgroup $groupName -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue 但当我这样做时,我得到了以下错误(我从错误中删除了任何特定于域的数据):
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我以为将ErrorAction和WarningAction设置为SilentlyContinue会阻止显示此错误,但事实并非如此。
发布于 2011-06-11 00:15:49
try {get-adgroup <groupname>}
catch {
<make new group>
}发布于 2012-02-24 05:06:22
我发现这样做效果最好:
$Group = Get-ADGroup -Filter {SamAccountName -eq $GroupName}如果筛选器不返回任何结果,则将$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."
}我发现,与mjolinor建议使用带有-Identity参数的Get-ADGroup cmdlet进行尝试/捕获相比,在逻辑上更容易处理(如果组存在,则添加用户;如果不存在,则显示一条消息)。考虑使用-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."
}您可以查看try块中的任何命令是否抛出终止错误。如果存在,则意味着该组不存在,并将继续处理catch块中的命令。它会起作用,但我认为与if/else相比,在逻辑上,try/catch here的流程不是很好。
别误会,mjolinor是个PowerShell天才。只是在这种情况下,我不认为他的解决方案是最好的。
发布于 2011-06-11 13:29:06
@mjolinor给出了很好的答案,但我认为一些解释也会有所帮助。
Windows PowerShell提供了两种报告错误的机制:一种是终止错误的机制,另一种是非终止错误的机制。
当发生不允许或不应允许cmdlet继续处理其输入对象的错误时,内部CmdLets代码可以调用ThrowTerminatingError方法。脚本编写器可以使用exception来捕获这些错误。
当cmdlet可以继续处理输入对象时,内部CmdLets代码可以调用WriteError方法来报告非终止错误。然后,脚本编写者可以使用-ErrorAction选项来隐藏消息。
https://stackoverflow.com/questions/6307127
复制相似问题