Add users to groups as part of New-ADUser process?

This topic contains 2 replies, has 2 voices, and was last updated by  thickgit 4 years, 7 months ago.

  • Author
  • #7544


    Hi All,

    I'm using Import-Csv and New-ADUser to create a whole bunch of new users. This is working fine.

    However, we have 27 different Active Directory groups for the various company job roles. Each user only needs to belong to a single AD group to get everything they need.

    Is there a way of specifying group membership as part of the user creation process? I noticed there's no '-memberof' parameter in New-ADUser or Set-ADUser.

    I'm already using 'Foreach-Object'. Can I use it again in the same line?

    I've also tried to put the whole command in parentheses like this:

    Add-ADGroupmember 'AD Role Group' (Import-Csv Users.csv | For-Each {New-ADUser etc.etc})

    (Kinda suspected that wouldn't work before I tried).

    Any suggestions?


  • #7545

    Don Jones


    First, add -PassThru to your New-ADUser command, and assign the output of the command to a variable.

    $user = New-ADUser -PassThru -Etc -Blah -Whatever

    You see, you need to stop doing everything as a giant one-liner. The $user variable can then be used in one or more subsequent calls to Add-ADGroupMember. In your CSV, just add a GroupName field.

    $users = Import-CSV users.csv

    ForEach ($user in $users) {

    $newuser = New-ADUser -PassThru -Name $user.Name -whatever -etc

    Add-ADGroupMember $User.GroupName $newuser


    As soon as you're doing more than one thing, you need to start thinking like a script, not like a ginormous one-liner.

  • #11053


    Hi Don,

    Many thanks for this. Due to my limited experience/knowledge of Powershell at the time, I still struggled with this task. I haven't had to create any AD accounts for a while, but I've been using Powershell for various tasks every day since.

    We've just had a bunch of new user requests come in, so I revisited this script. I've got it working now. (Would never have known to use the -Passthru switch).



You must be logged in to reply to this topic.