NOTE: Be sure to change the Temp user/group entries in $NewGroup and $BaseOU to your required distinguished names.

# 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=Temp User,OU=Temp User Groups,$DomainNC”
$NewGroup.GetInfoEx(@(“primaryGroupToken”), 0)
$NewGroupToken = $NewGroup.Get(“primaryGroupToken”)

# Determine which accounts will be effected by the change
$BaseOU = [ADSI]”LDAP://OU=Temp Users,OU=Temp User Groups,$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)
}

Reference:
http://www.indented.co.uk/2010/01/22/changing-the-primary-group-with-powershell/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s