Search code examples
arrayspowershellimport-csv

Array first element


I am trying to split an array read off a csv file and I cannot capture anything but the first array element. Here is my code

$EmployeeLists = @()
$ManagerLists = @()

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

ForEach($CSVFile in $CSVFiles) { $EmployeeLists += ($CSVFile.Employee) }
ForEach($CSVFile in $CSVFiles) { $ManagerLists += ($CSVFile.Manager) }

ForEach($EmployeeList in $EmployeeLists) { $EmployeeLists.Split(",")[0] | Out-File "C:\T2\SetManagers\ESplit.txt" -Append }
ForEach($ManagerList in $ManagerLists) { $ManagerLists.Split(",")[0] | Out-File "C:\T2\SetManagers\MSplit.txt" -Append }

My put put looks like this

Smith
Smith
Smith
Smith
Smith
Smith
Smith

Solution

  • Proper formatting goes a long way:

    $csv = Import-Csv -Path C:\T2\SetManagers\EmployeeManager.csv
    
    foreach ($list in $csv) {
        $list.Employee.Split(',')[0] | Out-File -Path C:\T2\SetManagers\ESplit.txt -Append
        $list.Manager.Split(',')[0] | Out-File -Path C:\T2\SetManagers\MSplit.txt -Append
    }
    

    Your problem was referring to the overall list instead of a single element in your foreach loops.