...Because someone's gotta tell the story...


To return to the main Blog List, click Full Blog Listing.


Active Directory

PS without BS: Fixing the user primary group

Saturday, February 03, 2018 in Active Directory (Views: 1177)
This is a Part 2 from the blog Group membership isn't consistent in AD Users and Computers. In this blog, I will go though a remediation script on how to set all user accounts to the primary group of "Domain Users". For more information on the backstory, see the link.

Now, to the script. There are a few things to point out:
  • This was tested to work with a single domain and all subdomains.
  • Domain Users is actually a privileged group, so not every user may be in it.
  • Before changing the primary group, always insure the user is a member (you can't just assume this).
  • Although the Domain Users group is consistent (that is the referenced 513), I added the step of checking the Groups for good measure.
  • The Domain Guest account should not be a member of Domain Users.
Below is the script that will set all users primary group to Domain Users and add them to the group if needed.


Function ProcessUser($strUser,$strDomain){
$GroupID = (Get-ADGroup -Identity "Domain Users" -Server $strDomain).SID
$PrimaryGroupID = $GroupID.Value.Substring($GroupID.Value.LastIndexOf("-")+1)

#Need to check to make sure the user is a member of Domain Users before we add it.
if (-Not (Get-ADGroupMember -Server $strDomain -Identity "Domain Users" | Where-Object {$_.SamAccountName -eq $strUser})){
Write-Host "Adding $strUser to Domain Users"
Add-ADGroupMember -Identity "Domain Users" -Server $strDomain -Members $strUser
#Now that the group membership is checked, set the primary group.
Set-ADUser -Identity $strUser -Server $strDomain -Replace @{primaryGroupID=$PrimaryGroupID}

Function ProcessDomain($strDomain){
$UserScan=(Get-ADUser -Filter {PrimaryGroupID -ne 513 -and SAMAccountName -ne "Guest"} -Server $strDomain)
foreach ($User in $UserScan){
#Increase the counter and process the user for setting their primary group
ProcessUser $User.SamAccountName $strDomain
} #end foreach

write-host $Domain": $intusers users fixed."

$adDomain=Get-ADdomain $RootDomain

#Process the root domain
ProcessDomain -strDomain $Domain)

foreach($Domain in $adDomain.childdomains)
#Start processing users from subdomains
ProcessDomain -strDomain $Domain

Happy Scripting!


Related Blogs You May Be Interested In:

To leave a comment, please log in and/or register.