PowerShell-将排除添加到remove -adgroupmember命令中?
当有人离开我的组织时,我们将删除所有广告组成员资格,除了primaryGroup
是域用户
。我们经常分批处理这些,因此从CSV文件中提取受影响的用户名。
我有以下代码,尽管它完成了删除所有组成员身份的工作,但我会为每个用户遇到一个错误:
无法从组中删除用户,因为该组是当前用户的主要组
而该组完成了工作,我该如何“清理”该过程以每次避免此消息?有没有一种方法可以将域用户从其删除用户中删除的组中排除,还是我应该以另一种方式执行此操作?
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
Get-ADPrincipalGroupMembership -identity $user.username | foreach {Remove-ADGroupMember $_ -Members $user.username -Confirm:$false}
}
When somebody leaves my organization, we remove all AD group memberships apart from the PrimaryGroup
which is Domain Users
. We often process these in batches, so pull the affected usernames from a CSV file.
I have the following code, and while it does the job of deleting all group memberships, I get an error for each user:
The user cannot be removed from a group because the group is currently the user's primary group
Whilst it does the job, how can I "clean up" the process to avoid this message each time? Is there a way to exclude Domain Users
from the groups it removes the user from, or should I do this another way?
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
Get-ADPrincipalGroupMembership -identity $user.username | foreach {Remove-ADGroupMember $_ -Members $user.username -Confirm:$false}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
如果在ADGROUP
会员身份之前获取aduser
对象,则可以获取用户的primary group
,并确保从中删除的组列表不是其primarygroup
:
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
$primaryGroup = ( Get-ADUser $user.UserName -Properties PrimaryGroup ).PrimaryGroup
Get-ADPrincipalGroupMembership -Identity $user.UserName | Where-Object {
$_ -ne $primaryGroup
} | ForEach-Object {
Remove-ADGroupMember $_ -Members $user.username -Confirm:$False -WhatIf
}
}
由于这有可能成为非常破坏性的命令,因此我在上面的示例中包括了一个保障。从中删除
实际执行删除。-Whatif
参数> remove-Adgroupmember
我建议的方法略有不同 - 只需删除Get -AdprincipalGroupMembership
。例如:
$users = Import-Csv -Path c:\temp\leavers.csv
foreach ($user in $users) {
# Assuming DN is not in the csv...
$distinguishedName = (Get-ADUser -Identity $user.UserName).DistinguishedName
Get-ADGroup -LdapFilter "(member=$distinguishedName)"
# Alternatively, just pipe memberOf property to Get-ADGroup...
(Get-ADUser -Identity $user.UserName -Property MemberOf).MemberOf |
Get-ADGroup
}
这样,您就不必过滤出您坚持要获得的东西(使用上述cmdlet)。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以使用
where-object
来过滤那些不在中的组组数组以排除的组。如果您只想过滤1个特定组,则在下面的示例中使用-ne
而不是-Notin
。You can use
Where-Object
for filtering those groups that are not in an array of groups to exclude. In case you only want to filter for 1 specific group, you would use-NE
instead of-NotIn
in below example.