title: PowerShell Import CSV to add Active Directory Security Groups
body: <p>I have a CSV from a client with a few columns in it. A column for Email, SamAccountName, SecurityGroups.</p>
  
  <p>In the Security Group column, each Security Group is separated by a ','
  Each row would look like below</p>
  
  <pre><code>User1 User1@email.com SecurityGroup1, SecurityGroup2, SecurityGroup3
  User2 User2@email.com SecurityGroup1, SecurityGroup2, SecurityGroup3
  User3 User3@email.com SecurityGroup13, SecurityGroup5, SecurityGroup6
  </code></pre>
  
  <p>A list of users in different Security groups, how do I go about reading the CSV and only adding the Security Groups each user needs.</p>
  
  <p>Below is what I have so far, when I run it in WhatIf mode it adds all the security groups to one user.</p>
  
  <pre><code>Clear
  $ADGroup = $null
  $i = 0
  $ADGroup  = import-csv 'File.csv'
  $sADGroup = $ADGroup.'Groups required'
  Import-CSV "TestUsers.csv" | % {  
      $SAM = $_.SamAccountName
      $ADUser = Get-Aduser -filter {SamAccountName -eq $SAM} -Properties * | Select SamAccountName, MemberOf
      Write-Host 'SamAccountName :' $_.SamAccountName ' - ADUser - '  $SAM
      $sADGroup | ForEach-Object{
              Write-HOst $ADGroup.ADgroup[$i]
              Add-ADGroupMember $sADGroup.split(",")[$i] -Members $ADUser.SamAccountName -WhatIf
              $i += 1
              }
      }
  </code></pre>