adding multiple users to multiple security groups

Bo Bøgsted 1 Reputation point
2021-09-28T08:26:40.33+00:00

Hello Technet.

I'm trying to look around after scripts that can handle adding multiple users to AD security groups just by looking after an " X " in a either a CSV or excel file,
acordingly to line where the X is

but I can't seam to find anything usefull only ones that need the group name instead of the X

135720-capture.png

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,951 Reputation points
    2021-09-28T19:00:44.76+00:00

    I've generalized you problem a little bit. The one you presented is limited to adding each user to only a single group. But what if you had to add each user to one or more groups? The code below will work with one or more users to be added to each group:

    [array]$ColumnsToOmit = "User names"  
      
    $ColumnsToScan = @()  
    $groups = @{}  
    [array]$data = Import-Csv c:\junk\g.csv  
      
    $ColumnsToScan =    $data[0] |  
                            Get-Member -MemberType NoteProperty |   
                                Select-Object -expand name |  
                                    Where-Object {$ColumnsToOmit -notcontains $_}  
    ForEach ($user in $data) {  
        ForEach ($ColumnName in $ColumnsToScan){  
                if ($user.$ColumnName -eq 'x'){  
                    [array]$groups[$ColumnName] += $user."User names"  
                }  
            }  
        }  
    $groups.GetEnumerator() |  
        ForEach-Object{  
    #       "Adding $($_.Value) to $($_.Name)"  
            Add-ADGroupMember -Identity $_.Name -Members $_.Value  
        }  
    
    
      
      
    
    0 comments No comments

Your answer

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