Adding AD users to multiple groups


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.

Please read the help for Add-ADPrincipalGroupMembership - that’s all you need. :wink: 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

Ohh, I see. That’s excellent.

Thanks very much!

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.

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.