PS without BS: Fixing the user primary group
This is a Part 2 from my 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 considered a privileged group, so not all users may be members.
- 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.
$RootDomain=(Get-ADDomain).Forest
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){
$intUsers=0
$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
$intUsers++
ProcessUser $User.SamAccountName $strDomain
} #end foreach
write-host $Domain": $intusers users fixed."
}
$adDomain=Get-ADdomain $RootDomain
$Domain=$adDomain.DNSRoot
#Process the root domain
ProcessDomain -strDomain $Domain)
foreach($Domain in $adDomain.childdomains)
{
#Start processing users from subdomains
ProcessDomain -strDomain $Domain
}
Happy Scripting!
— Easy link to my blog: https://aka.ms/leesteve —
If you like my blogs, please share it on social media and/or leave a comment.