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 = $OldGroup.Get("primaryGroupToken")

$NewGroup = [ADSI]"LDAP://CN=Domain Guests,CN=Users,$DomainNC"
$NewGroup.GetInfoEx(@("primaryGroupToken"), 0)
$NewGroupToken = $NewGroup.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() | ForEach-Object {
    $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)
}