gpt4 book ai didi

powershell - 使用 Get-ADGroup 时隐藏错误

转载 作者:行者123 更新时间:2023-12-02 23:46:31 24 4
gpt4 key购买 nike

我正在编写一个脚本,如果它不存在,它将构建一个新组。我使用 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 会阻止显示此错误,但事实并非如此。

最佳答案

我发现这样效果最好:

$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 进行 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."
}

您会看到 try block 中的任何命令是否抛出终止错误。如果这样做,则意味着该组不存在,并将继续处理 catch block 中的命令。它会起作用,但我认为与 if/else 相比,这里的 try/catch 从逻辑上讲并不流畅。

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

关于powershell - 使用 Get-ADGroup 时隐藏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com