![检查现有 AD 组成员在 PowerShell 中不起作用](https://linux22.com/image/742244/%E6%A3%80%E6%9F%A5%E7%8E%B0%E6%9C%89%20AD%20%E7%BB%84%E6%88%90%E5%91%98%E5%9C%A8%20PowerShell%20%E4%B8%AD%E4%B8%8D%E8%B5%B7%E4%BD%9C%E7%94%A8.png)
我有一个 50% 的工作脚本,用于将用户添加到 AD 组。但我无法完成需要检查他们是否已经是该组成员的部分。
请参见以下失败的部分:
ForEach ($Group in $Groups) {
$Members = Get-ADGroupMember -Identity $Group -Recursive | where {$_.objectclass-eq “user”} | Select sAMAccountName
If ($Members -contains $User) {
Write-Host "$User is already member of" Test.$Space.Admin
}
如果用户已经是 AD 组的成员,则不会向我提供更新。
完整代码如下:
$Space = "MS"
$ADMAccount = "john.smith","jane.smith"
$USRAccount = "john.doe","jane.doe"
$VWRAccount = "something.special","other.user"
$Groups = "Test.$Space.Admin","Test.$Space.Users","Test.$Space.Viewers"
Write-Host "Adding users to AD Groups now..." -ForegroundColor White
ForEach ($User in $ADMAccount){
ForEach ($Group in $Groups) {
$Members = Get-ADGroupMember -Identity $Group -Recursive | where {$_.objectclass-eq “user”} | Select sAMAccountName
If ($Members -contains $User) {
Write-Host "$User is already member of" Test.$Space.Admin
}
Else {
Add-ADGroupMember -Identity "Test.$Space.Admin" -Members $ADMAccount
}
}
}
ForEach ($User in $USRAccount){
ForEach ($Group in $Groups) {
$Members = Get-ADGroupMember -Identity $Group -Recursive | where {$_.objectclass-eq “user”} | Select sAMAccountName
If ($Members -contains $User) {
Write-Host "$User is already member of $Group"
}
Else {
Add-ADGroupMember -Identity "Test.$Space.Users" -Members $USRAccount
}
}
}
ForEach ($User in $VWRAccount){
ForEach ($Group in $Groups) {
$Members = Get-ADGroupMember -Identity $Group -Recursive | where {$_.objectclass-eq “user”} | Select sAMAccountName
If ($Members -contains $User) {
Write-Host "$User is already member of $Group"
}
Else {
Add-ADGroupMember -Identity "Test.$Space.Viewers" -Members $VWRAccount
}
}
}
Write-Host "Adding users to AD Groups completed..." -ForegroundColor Green
提前致谢,罗兰