我有一个 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
提前致谢,罗兰