Powershell: Adding security group membership to active directory users and computers

# this script adds members to given user security group

Clear-Host
$target = 'yourou'   # organizational unit
$group = "groupname" # group name

$gp = dsquery group -name $group
$gp = $gp -replace '"',''  

$user = Get-ADUser -SearchBase "ou=$target,dc=yourcompany,dc=com" -Filter * -ResultSetSize 5000 | Select Name,SamAccountName
$comp = Get-ADComputer -SearchBase "ou=$target,dc=yourcompany,dc=com" -Filter * -ResultSetSize 5000 | Select Name,SamAccountName

#--------------add users that are in the given ou to the group

foreach ($u in $user){   
        $userName = (Get-ADUser -Identity $u.SamAccountName -Properties MemberOf,sAMAccountName | Select-Object MemberOf,sAMAccountName)
        if (-not ($username.MemberOf -match $group)){
            Write-Host("user $u.SamAccountName is not a member of $group now being added")
            Add-ADGroupMember -Identity $group -Members $username.sAMAccountName
            }
        else{
            Write-Host("user $u.SamAccountName is already a member of group $group")
        }
      }
#--------------add computers in the given ou to the group
{
foreach ($u in $comp){   
        $compName = (Get-ADComputer -Identity $u.SamAccountName -Properties MemberOf,SamAccountName | Select-Object MemberOf,SamAccountName)
        if (-not ($compName.MemberOf -match $group)){
            Write-Host("computer $u.SamAccountName is not a member of $group now being added")
            Add-ADGroupMember -Identity $group -Members $compName.SamAccountName
            }else{
                Write-Host("computer $u.SamAccountName is already a member of group $group")
        }
      }
}

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir


− 8 = one

Şu HTML etiketlerini ve özelliklerini kullanabilirsiniz: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Yandex.Metrica