Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 516
JRN Avatar asked Jan 21 '26 14:01

JRN


2 Answers

$Employee = $CSVFiles | Select -Expand Employee
$Manager  = $CSVFiles | Select -Expand Manager
like image 118
iRon Avatar answered Jan 23 '26 04:01

iRon


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
}
like image 36
Vivek Kumar Singh Avatar answered Jan 23 '26 04:01

Vivek Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!