Interlude III : Setting Primary Group ID

Ran into an interesting situation at work today. An account had had the primary group changed from the Domain Users group to another group and then the Domain Users membership was removed. Needless to say, this caused some issues with an application that was granting rights based on membership to the Domain Users group. That got me thinking about how to set the primary group on an account without having to root around inside the ADUC utility.

Setting this is pretty simple from a PowerShell perspective. Fisrt we need to find the SID of our desired primary group. To do this we use the following:

$groupsid = (Get-ADGroup "group name").sid

This gets us the SID information in a variable where we can work with it. Notice I said “where we can work with it” versus just “in a variable”. If you look at the variable contents you’ll find we have more than just the SID.

[PS]>$groupsid | fl
BinaryLength : 28
AccountDomainSid : S-1-5-21-<SID stuff here>
Value         : S-1-5-21-<SID stuff here>-513

We actually have three values : the binary length, the domain SID the group is in, and the full SID of the group. We need to be concerned with only the Value, and specifically only with the last bit, 513. To get that portion we’re going to use two string functions – LastIndexOf and Substring. The LastIndexOf is going to give us the position of the last occurrence of the character “-” which comes just before the group ID (513). By adding one to that and using the Substring function we’ll be able to get everything to the right of that. We’ll place this into a variable that is defined as an integer value since the property on the user object has to be an integer value.

[int]$primarygroupid = $groupsid.Value.Substring($groupsid.Value.LastIndexOf("-")+1)

Finally we can update the user object with the primary group ID value

Set-ADUser "user" -Replace @{primaryGroupID=$primarygroupid}

Comments are closed.