0

I need to move ADUsers to each ADGroup they are listed under each column, the columns are the group names themselves so $_.groups since there are no headers.

Example CSV

2 Answers 2

1

You would need to loop through the column headers. You can obtain a list of these properties by using the Get-Member cmdlet.

$usersToAdd = Import-CSV users.csv
$groups = ($usersToAdd | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" }).Name

From here you could loop through the groups querying the members that fall under each group in the original csv.

foreach ($group in $groups) {
    $users = $usersToAdd.$group
    foreach ($user in $users) {
        Add-ADGroupMember -Identity $group -Members $user -Confirm:$false
    }
}

You may get some empty values if some columns have more users than others do, so perhaps you will want to check for that too.

foreach ($group in $groups) {
    $users = $usersToAdd.$group
    foreach ($user in $users) {
        if (![string]::IsNullOrEmpty($user)) {
            Add-ADGroupMember -Identity $group -Members $user -Confirm:$false
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Thank you for your response Ash! I will try this shortly to confirm. I found this script online that worked rather well Though I am still breaking this down to fully understand it. Thank you again for your help!!::

> $rows = Import-Csv "C:\FILE.csv" 
> $groups = @{} 
> foreach ($header in $rows[0].PSObject.Properties.Name) { $groups[$header] = @() } 
> foreach ($row in $rows) 
> {
>     [string[]]$keys = $groups.Keys
>     foreach ($key in $keys)
>     {
>         if ($row.$key) { $groups[$key] += $row.$key }
>     }
> } 
>foreach ($key in $groups.Keys) { Add-ADGroupMember -Identity $key -Members $groups[$key] -Verbose }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.