问题描述
我正在尝试制作一个PS脚本,该脚本将列出所有Active Directory用户组成员身份(递归).
I'm trying to make a PS script which would list all Active Directory user group membership (recursive).
我已经有有效的脚本:
import-module activedirectory
$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' }
$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"
foreach ($user in $users)
{
$groups = Get-ADPrincipalGroupMembership $user
foreach ($group in $groups)
{
$username = $user.samaccountname
$groupname = $group.name
$line = "$username;$groupname"
Add-Content $targetFile $line
}
}
但是脚本不会递归列出组,即,如果输出文件中列出的组是另一个组的一部分.
But script doesn't list groups recursively, i.e., if group listed in the output file is part of another group.
示例:
Group1:用户
Group2:Group3:用户
Group2: Group3: User
脚本仅显示第1组和第3组,而不显示第2组.
Script shows only Group1 and 3 but not 2.
我应该在第一个以递归方式写入组成员身份的脚本中添加什么?
What should I add to the first script that it writes group membership recursively?
推荐答案
对不起,我正在发布3年前的问题的答案,但是如果有人看到它,它会有所帮助.
归功于:
如何获取所有AD用户Powershell或其他工具(递归)分组?
Sorry I am publishing an answer for a question from 3 years ago but if someone will see it, it can help.
Credit to:
How to get ALL AD user groups (recursively) with Powershell or other tools?
您可以使用 LDAP_MATCHING_RULE_IN_CHAIN :
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=CN=User,CN=USers,DC=x)"
在可以使用LDAP过滤器的任何地方都可以使用它.
You can use it anywahere that you can use an LDAP filter.
示例:
$username = 'myUsername'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name
修正您的脚本:
import-module activedirectory
$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' }
$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"
foreach ($user in $users)
{
$dn = $user.DistinguishedName
$groups = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name
foreach ($group in $groups)
{
$username = $user.samaccountname
$groupname = $group.name
$line = "$username;$groupname"
Add-Content $targetFile $line
}
}
这篇关于使用Powershell获取所有AD用户的递归组成员身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!