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

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,734 questions
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,579 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,466 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 Answers by the question author, which helps users to know the answer solved the author's problem.