Search code examples
arrayspowershellimport-csv

Loading two arrays from a CSV


I have a CSV File that has two columns Employee and Manager and I would like to import them into two Variables for use later in my script. However when I run my code it only captures the last data item in the CSV as the previous one is being over written.

$CSVFiles = Import-CSV "C:\T2\EmployeeManager.csv"

ForEach($CSVFile in $CSVFiles)
{
  $Employee = ($CSVFile.Employee); $Manager = ($CSVFile.Manager)
}

Solution

  • That's because you are overwriting the added data each time the loop runs. IN PowerShell the += appends to an object. Try this -

    $Employee = @()
    $Manager = @()
    
    $CSVFiles = Import-CSV "C:\T2\EmployeeManager.csv"
    
    ForEach($CSVFile in $CSVFiles)
    {
      $Employee += $CSVFile.Employee; $Manager += $CSVFile.Manager
    }