Question

First I have to say I've this and this thread already, but couldn't figure out an answer from those.

I have a CSV file looking like this:

Username,Groups
User01,Group01;Group02;Group03
User02,Group10;Group24;Group08
User03,Group13;Group02;Group42

etc etc... There are hundreds of users and hundreds of different groups in total, so splitting individual users and/or groups to their own lines manually is not really an option.

I cannot figure out the logic how to process the lines with foreach while splitting the imported CSV twice with different delimiters and then foreach the groups per user again. Any ideas..?

Was it helpful?

Solution

You can split groups on ; character, so if you want add users to groups use this:

$src = Import-Csv yourfile.csv
foreach($line in $src){
    $user = $line.Username
    $groups = $line.Groups -split ";"
    foreach($group in $groups){
        Add-ADGroupMember -Identity $group -Members $user
        # other code which uses $group and $user
    }
}

OTHER TIPS

You probably want something like

$Line = import-csv yourfile.csv
#Skip first line here
 foreach ($Data in $Line)
 {
  $User = $Data.v1
  $Group1 = $Data.v2
  $Group2 = $Data.v3
  $Group3 = $Data.v4

  write-host "User: "$User
  write-host "Group1: "$Group1
  write-host "Group2: "$Group2
  write-host "Group3: "$Group3
  Write-Host ""
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top