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() | %{
  $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)
}

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

2 Comments

  1. Working with AD groups in PowerShell - Admins Goodies says:

    [...] Changing Primary Group with Powershell [...]

  2. Jeremy Saunders says:

    Nice script! You can wrap this in a function and change the following two lines to be able to change the Primary Group on a per user basis.

    $BaseOU = [ADSI]“LDAP://$DomainNC”
    $LdapFilter = “(&(objectClass=user)(objectCategory=person)(primaryGroupId=$OldGroupToken)(sAMAccountName=$Member))”

    Cheers,
    Jeremy.

Leave a Reply