How to change the primary group of an AD user?

In the past I have made a PowerShell script that did some cleanup in the Active Directory on accounts of former employees. Like disable their account, move to a different OU and archive home and profile directory. In that script I use the Quest AD Cmdlets for all the AD actions. Although I like these cmdlets, I wanted to modify the script so that it uses the built-in AD cmdlets that are built in Windows Server 2008 R2.

Replacing the Quest AD Cmdlets with the built in cmdlets was not very difficult. But I had one little problem. We prefer to remove old accounts from all the groups they belong to. This way you will not find disabled or not existing accounts in the groups. But one group is assigned as the Primary Group and you cannot remove a user from this group. Default this is the ‘Domain Users’ group.

In the old script we added the user account to a special group called ‘Former Employees’, make this the Primary Group and remove all the other groups including ‘Domain Users’. With the Quest AD Cmdlets is fairly easy to do with the cmdlet Set-QADuser. Unfortunately this was not possible with the cmdlet Set-ADuser.

I tried to find a solution with Google but was not very successful. All the answers I found refer to ADSI or the Quest AD Cmdlets. So I have made my own function for this using the built-in AD Cmdlets from Windows Server 2008 R2. The user has to be a member of the group before you can make it the Primary Group!

Function Set-PrimaryGroup {
    Param (
        [string]$username=$(Throw "Error: Please enter a username!"),
        [string]$groupname="Domain Users")

Process {
    Try {
        #Get the DistinguishedName of the user for you want to change the primary group
        $UserDistinguishedName = (get-aduser -Identity $username -ErrorAction Stop).DistinguishedName
        Try {
            #Get SID of the Group that will become the primary group
            $GroupSid = (Get-ADGroup -Identity $groupname -Properties PrimaryGroupID -ErrorAction Stop).SID

            #Get the last 4 digits of the SID to become te PrimaryGroupID
            $PrimaryGroupID = $GroupSid.Value.Substring($groupsid.Value.LastIndexOf('-')+1)

            #Replace the PrimaryGroupID of the user with its new value. The user has to be already a member of this group.
            Set-ADObject -Identity "$UserDistinguishedName" -replace @{PrimaryGroupID=$PrimaryGroupID}
            Write-Host "$groupname set as primary group for user $username"
        } Catch {
            Write-Host "Error: Unable to find the PrimaryGroupID for group $GroupName! Maybe the group does not exist." -ForegroundColor red
        }
    } Catch {
        Write-Host "Error: Unable to find user $username!" -ForegroundColor red
    }
  }
}
Advertisements