Changing the Primary Group with PowerShell
Exactly as the title says, an example of how to change the Primary Group for a set of users returned by a search with PowerShell.
# The current Domain
$DomainNC = ([ADSI]"LDAP://RootDSE").DefaultNamingContext
# The Primary Group Token for Domain Users and Guests will always be
# the same value (no matter the forest). Used as a demonstration of
# how the value can be retrieved
$OldGroup = [ADSI]"LDAP://CN=Domain Users,CN=Users,$DomainNC"
$OldGroup.GetInfoEx(@("primaryGroupToken"), 0)
$OldGroupToken = $DomainUsers.Get("primaryGroupToken")
$NewGroup = [ADSI]"LDAP://CN=Domain Guests,CN=Users,$DomainNC"
$NewGroup.GetInfoEx(@("primaryGroupToken"), 0)
$NewGroupToken = $DomainGuests.Get("primaryGroupToken")
# Determine which accounts will be effected by the change
$BaseOU = [ADSI]"LDAP://OU=SomeWhere,$DomainNC"
$LdapFilter = "(&(objectClass=user)(objectCategory=person)" + `
"(primaryGroupId=$OldGroupToken))"
# Find the users
$Searcher = New-Object DirectoryServices.DirectorySearcher($BaseOU, $LdapFilter)
$Searcher.PageSize = 1000
$Searcher.FindAll() | %{
$User = $_.GetDirectoryEntry()
# The user must be a member of the group first
$NewGroup.Add($User.AdsPath)
# Change the Primary Group
$User.Put("primaryGroupId", $NewGroupToken)
$User.SetInfo()
# Then the old group can be removed
$OldGroup.Remove($User.AdsPath)
}
Related posts:
- Accept or reject messages from This function reads delivery restrictions from objects in Active Directory....
- Get-DsAcl The goal of this PowerShell function is to create a...
- Building LDAP filters for date based attributes Active Directory contains a number of attributes which hold date...
- PowerShell, IIS and log settings A function to retrieve IIS log settings from a local...
Related posts brought to you by Yet Another Related Posts Plugin.
Respond to this post