Durr
Durr

Reputation: 43

Output arrays to files

I have some code that imports a file, groups the data by jobtitle, and then creates an array named for each job title. Each array contains all of the employee IDs associated with that job title. I need to output the employee IDs for each job title to a separate file named for the job title. So I need to export the array called Customer Service to a file named Customer Service. The file needs to contain each of the employee IDs (the elements in the array).

I can export all employee IDs to a single file using:

Import-Csv $Results | Group-Object "jobtitle" | %{
    Set-Variable ($_.Name) ($_.Group | Select-Object -ExpandProperty ID | Add-Content $outfile)
}

However, I need the employee IDs for each job title to be in a different file named after the job title. So, I've tried ForEach-Object, foreach and the following, but can't get this right.

Import-Csv $Results | Group-Object "jobtitle" | %{
    Set-Variable ($_.Name) ($_.Group | Select-Object -ExpandProperty ID |  Set-Content {"C:\Users\$env:username\Documents\Results\$_.Name $_.Group"})
}

Upvotes: 1

Views: 448

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Just define the output filename inside the loop and write the IDs to the file:

Import-Csv $Results | Group-Object "jobtitle" | ForEach-Object {
    $file = 'C:\some\folder\{0}.txt' -f $_.Name
    $_.Group | Select-Object -Expand ID | Set-Content $file
}

Upvotes: 1

Related Questions