检查用户是否是AD组列表的成员
问题描述:
$groups = 'group1', 'group2'....
我需要检查用户是否在特定的AD组中,如果不在,则回显该组名;我可以在管道中这样做吗?
I need to check if the user is in a specific AD group and echo the group name if he is not ; can I do it in the pipeline?
我在Google上搜索了很多东西,却找不到任何东西,也许我对Google的英文搜索不太满意:)。
I have googled a lot and cannot find anything, maybe I am too bad at Google search in English :).
$groups |
Get-QADGroupMember |
Get-QADUser -SamAccountName 'lalala' | ForEach-Object {
if ($_.SamAccountName -ne $null) {
Write-Host "ok"
} else {
Write-Host 'not ok'
}
}
如何显示:不正确。用户不在
group_name
?
How can I display: not ok. user is not in
group_name
?
答
问题是,为什么仅在遍历结果如此简单的情况下为什么要使用管道?
The question is why do you want to use the pipeline when just looping through the results is so easy?
要检查用户是否组列表中的成员:
To check if a user is a member of a list of groups:
$user = "TestUsername"
$groups = 'Domain Users', 'Domain Admins'
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $user) {
Write-Host "$user is a member of $group"
} Else {
Write-Host "$user is not a member of $group"
}
}
对于多个用户:
$users = "TestUsername1", "TestUsername2", "TestUsername3"
$groups = 'Domain Users', 'Domain Admins'
foreach ($user in $users) {
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $user) {
Write-Host "$user is a member of $group"
} Else {
Write-Host "$user is not a member of $group"
}
}
}