Adding AD users to multiple groups

Welcome Forums General PowerShell Q&A Adding AD users to multiple groups

Viewing 4 reply threads
  • Author
    Posts
    • #225753
      Participant
      Topics: 1
      Replies: 2
      Points: 35
      Rank: Member

      Hi,

      I’m new to creating PowerShell scripts but excited to get started. I’ve been working on a simple script to add an AD user to multiple groups using:

      $groups = 'group1','group2','group3'
      $username = Read-Host -Prompt 'Input the username'
      
      foreach($group in $groups){
          Add-ADGroupMember -Identity $group -Members $username
      }
      

      Which works fine but now instead of manually inputting the username at prompt I would like it to grab it from a list of multiple users in a text file say at c:\scripts\users.txt – and for it to add each of the users in the list to those groups.

      I’ve been looking at Get-Content and sample scripts but I can’t seem to get my head around where to fit it in exactly. Any help would be most appreciated.

      Thanks in advance.

    • #225762
      Participant
      Topics: 4
      Replies: 2249
      Points: 5,494
      Helping Hand
      Rank: Community MVP

      Please read the help for Add-ADPrincipalGroupMembership – that’s all you need. 😉 You should read the completely including the ewxamples to learn how to use it.

      $groups = 'group1', 'group2', 'group3'
      $userList = Get-Content -Path '.\UserList.txt'
      
      foreach ($user in $userList) {
          Add-ADPrincipalGroupMembership -Identity $user -MemberOf $groups
      }
    • #225768
      Participant
      Topics: 1
      Replies: 2
      Points: 35
      Rank: Member

      Ohh, I see. That’s excellent.

      Thanks very much!

    • #225774
      Participant
      Topics: 4
      Replies: 12
      Points: 89
      Rank: Member

      Since you mentioned you’re still new to PowerShell scripting – beyond Get-Content, I’d also highly recommend looking into Import-Csv, and Export-Csv. They’re great for folks who aren’t ready for the power/headache of XML with Import/Export-Clixml, but they also give a simple way to store “objects” in a way that’s very easy for powershell to parse. Even if you only have one column called Name, when you do import-csv -path .\UserList.csv, you’ll get a PSObject Array, where each object has a Name property.

      It would be overkill for this example, but it’s a great place to start looking next, and it might give you ideas for your next script.

    • #225780
      Participant
      Topics: 1
      Replies: 2
      Points: 35
      Rank: Member

      Thanks for that, I’ll have a read around those and try incorporate them somewhere when needed.

      I’m certainly looking to develop my skills and get more basic tasks automated to begin with before delving into the big stuff, so that’s a great help in getting there.

Viewing 4 reply threads
  • You must be logged in to reply to this topic.