Just the last line in csv is executed

Hello,

In my script I import a csv file with mutliple rows , groups and users.
However only the last row is executed and I do not see why

It does not show a error by looking up the users, however by adding users to the group it is telling me that the user in the first row cannot be found

My CSV file looks like: $data

domain Adgroup Account


Pieter.com rol-adgroup-function-01 user1,user2,user3
Pieter.com rol-adgroup-function-02 user4, user5

My script:

Import-Module ActiveDirectory

$data = import-csv "P:\users\PieterB\Scripts\CSV\addgroup.csv" -Delimiter ";"

#check if the user exists in the domain
# Split because the users are all in 1 row separated by a ,


$Sam = foreach ($account in $data){
    $User= $account.account.Split(',')
   
    foreach($entry in $user){
    Get-Aduser $entry -Server $account.domain  |select -ExpandProperty samaccountname
    }
    If ($entry -ne $null) {
    "$User is found in $UserDomain"
    }
    else
    {
    "Useraccount $entry is/zijn niet gevonden in $UserDomain"
    }
     }
     
 #check if the ADgroup exists in  AD
foreach ($Item in $Data){
$ADG = $group.split(',')
}
 
    Foreach($group in $ADG){
     $ADG = Get-ADGroup $Item.adgroup -Server $item.domain
     If (!$ADG)
        { write-host "adgroup $($item.adgroup) not found in AD"
    }
    else
    {
    add-ADGroupMember -Identity $ADG -Members $Sam -server $item.domain
    }
     
#to add the text neccesary for the ticket comment

"De user is toegevoegd aan de Adgroep(en): `n`n$($Group | % {"$($_.Trim())`n"})".Split("`n") | % {$_.TrimStart()} | Set-Clipboard

For the experts likely ths a “aha …” moment…:slight_smile:
For me it will be another lesson learned and it is appreciated.

thx

Your code is quite confusing. You know your 3 foreach loops run independently from each other, don’t you? … except of the nested loop inside your first foreach.

In your second foreach loop …

#check if the ADgroup exists in  AD
foreach ($Item in $Data) {
    $ADG = $group.split(',')
}

… you define $item as the loop variable but you use $group inside the loop. And since you’re assigning the variable $ADG inside your loop it will be overwritten each time your loop runs until the last item. :wink:

In your last foreach loop the variable names do not fit together either. $group vs $item … and on top of that you define the variable $ADG inside your loop while you’re using it for the loop control : Foreach ($group in $ADG) {

What is it actually what you’re trying to do?

1 Like

hello Olaf,

It looks like I need to do a better job creating my script … :innocent:
I will need to review the Loops in it, looks to me that I did the 1 thing that is making it very difficult.
Re-edit my script and not finish it properly then lose the perpective …pfffff
Anyway, with a proper written script and still a answer I will be happy to come again. :pray: