AD user objects within a variable

Evening All,

This has driven me CRACKERS all afternoon…

We got sent a csv file with about 30 group names in the first column and anything up to about 10 users, separated by commas, in each cell in the 2nd column.

Group User
Group1 User1,User2,User3,User4
Group2 User5,User6,User7,User8,User9,User10 etc.etc.

Using just the regular AD cmdlets (not Quest), I tried:

$users = Import-Csv c:\ADgroup.csv
foreach ($user in $users) {Add-ADGroupMember $users.group $users.user}

I couldn’t get PowerShell to recognise the users from the second column. I tried a number of ways to try and store them in an array etc. (I’m going from memory here…)

foreach ($user in $users){$list = @($users.user);
Add-AdGroupMember $users.group $list etc.etc.

It kept looking for all five users as a single user (i.e. error was something like “cannot find “User1,User2,User3,User4 etc” under domain company.pri”). I tried adding quotation marks around each user’s name, but that didn’t help either.

Can anyone shed any light on this?

Thanks in advance

Thick Git

You are doing for each USER in the USERS collection and then referencing the USERS in your loop:

$users = Import-Csv c:\ADgroup.csv
foreach ($user in $users) {Add-ADGroupMember $users.group $users.user}

Add-ADGroupMember has a Members variable that is a string array, so if you use Split, it will convert the comma separated users into an array. When you get data from a CSV, anything in that column is a string, so you have to convert the “users” into an array, something like this:

$csv = @()
$csv += New-Object -TypeName PSObject -Property @{Group="Group1";User="User1, User2, User3"}
$csv += New-Object -TypeName PSObject -Property @{Group="Group2";User="User5, User8, User3, User9"}
$csv += New-Object -TypeName PSObject -Property @{Group="Group3";User="User225, User82, User43, User59"}

$csv | foreach{
    $users = $_.User -Split ","
    Add-ADGroupMember -Identity $_.Group -Members $users -WhatIf
}

Many thanks Rob. I appreciate your taking the time to help. All the best. TG.

This is what happens underneath a foreach:

$array = 1..10

foreach($item in $array) { 
    Write-Host $item
}


for($i = 0; $i -lt $array.Count; $i++) {
    $item = $array[$i]
    
    Write-Host $item
}

What you can do with the for-loop, that you can’t do with foreach, is edit the array objects as you’re running through them:

$array = 1..10

for($i = 0; $i -lt $array.Count; $i++) {
    $array[$i] = $i
}

0
1
2
3
4
5
6
7
8
9

However with a foreach you can still edit the values of the object’s properties, if your objects have properties to edit that is:

$array = 1..10 | % { [pscustomobject]@{ Number = [int]$_ } }

foreach($item in $array) {
    $item.Number = 0
}

Number
------
0
0
0
0
0
0
0
0
0
0