Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#region Variable Definition
$dryRun = $true
$searchBase = (Get-ADDomain).DistinguishedName
#region Code below
#Gather the DomainSID
$domainSID = (Get-ADDomain).DomainSid.Value
#Fix on one DC so we don't run into replication problems after adding a user to a group
[string]$DCName = (Get-ADDomainController -NextClosestSite -Writable -Discover | Select-Object -First 1).Hostname
Get-ADUser -Filter * -Server $DCName -SearchBase $searchBase -Properties objectSid,sAMAccountName,primaryGroupID |
Where-Object {
#Sort out all users whose primaryGroup is not Domain-Users and not Domain-Guests
($_.PrimaryGroupID -ne "513" -and $_.PrimaryGroupID -ne "514") -or
#Handle the default Domain Guest Account
!($_.objectSid.Value -eq ($domainSID + "-501")) -xor
!($_.PrimaryGroupID -eq "514")
} |
ForEach-Object {
#Set a variable to the user object, since we won't be able to access it within the catch logic
$user = $_
$sAMAccountName = $user.sAMAccountName
#Get current primaryGroup
$oldPrimaryGroupID = $_.primaryGroupID
$expectedPrimaryGroupSID = ($domainSID + "-" + $oldPrimaryGroupID)
$expectedPrimaryGroup = Get-ADGroup -Filter { objectSid -eq $expectedPrimaryGroupSID } -Properties Member,sAMAccountName,distinguishedName -Server $DCName
#Determinate proper primary group
if($_.ObjectSid.Value -eq ($domainSID + "-501")){
$expectedPrimaryGroupID = 514
Write-Warning("Care: Default Domain Guest '$sAMAccountName' User was modified, please take a deeper look at this user.")
$expectedPrimaryGroupID = 513
#Set the primaryGroupID
Write-Host($sAMAccountName + ": Changing primaryGroupID")
$user | Set-ADUser -Replace @{ primaryGroupID = $expectedPrimaryGroupID } -Server $DCName
#Check if the user is already member of this group, otherwise add him
#We can't use Get-ADGroupMember as the cmdlet also returns users which only got this group set as primaryGroupSID
if(!($expectedPrimaryGroup.Member -contains $user.distinguishedName)){
#Add the user to his prior primaryGroup
Write-Host($sAMAccountName + ": Added user to $($expectedPrimaryGroup.sAMAccountName)")
Add-ADGroupMember -Identity $expectedPrimaryGroup -Members $user -Server $DCName
Write-Host($sAMAccountName + ": Successfully corrected primaryGroup.")
#Looks like it didn't work -> Set the primarySID to the old Value so we don't mess up anything
$user | Set-ADUser -Replace @{ primaryGroupID = $oldPrimaryGroupID } -Server $DCName
Write-Host($sAMAccountName + ": Failed to corrected primaryGroup, Error: " + $_.Exception.Message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment