Want to change the primary group of all users using an import file based on samaccountname

Eric 121 Reputation points
2022-07-13T15:11:59.77+00:00

Hello All,

Looking for help with the following script. Tried it together but no go. Can you help out please?

Want to change primary group membership from "Domain Users" to a group call "Identity"

$group = get-adgroup "Domain Users"
$groupSid = $group.sid
$GroupID = $groupSid.Value.Substring($groupSid.Value.LastIndexOf("-")+1)
Import-module ActiveDirectory
Import-CSV "C:\Users.csv" -Member $_.UserName | % {Set-ADObject -Replace @{primaryGroupID="$GroupID"}}

The import file is a csv file with the column header "samaccountname"

Thank you for your help

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,621 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rafael da Rocha 5,251 Reputation points
    2022-07-13T19:06:54.663+00:00

    Maybe something like this:

    Import-Module ActiveDirectory  
    $Users = Import-CSV "yourfile.csv"  
    $Group = Get-ADGroup "Identity" -Properties @("primaryGroupToken")  
      
    foreach ($User in $Users){  
     Set-ADUser $User.SamAccountName -Replace @{primaryGroupID=$group.primaryGroupToken}  
     }  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 47,596 Reputation points
    2022-07-13T19:28:28.257+00:00

    I'd use this function: Set-ADUserPrimaryGroup.ps1

    2 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.