How Do I Correctly Output Data to a CSV File with PowerShell?

0
0
Asked By CuriousCoder42 On

I'm running into some issues with my PowerShell script and could use a hand. I haven't worked with PowerShell in a while, and I think I might be making a simple mistake. I'm trying to take the first two columns from a CSV file and replicate these for each entry in the third column. My goal is to have each person's name on its own row, accompanied by the corresponding group and description from the source file. The problem is that although it looks correct when I display each line as I work with the array, the output file shows the right number of rows but keeps repeating the last set of data for every row. Here's the code I'm using:

[array]$newCSV = @()
[PSCustomObject]$newitem = @{
Group = ''
Description = ''
Person = ''
}
[string]$srcFile = 'D:DataInput.csv'

$csv = Import-Csv $srcFile

foreach ($item in $csv) {
$group = $item.group
$desc = $item.description
$members = $item.members

foreach ($mbr in $members.Split(',')) {
$newItem.group = $item.Group
$newItem.description = $item.Description
$newItem.person = $mbr
$newCSV += $newItem
}
}

$newCSV | Export-Csv -Path C:QTM-ExportsSNOW-Approvals-Results.csv -NoTypeInformation

Here's a sample of my data file:

"Group1","Description1","Bob,Sam,Fred"
"Group2","Description2","Bob"
"Group3","Description3","Bob,Sam,Dave,Mike"

Thanks a ton in advance!

1 Answer

Answered By HelpfulHarry77 On

Could you share an example of what your desired output looks like? Like, are you aiming for this format?
"Group1","Description1","Bob"
"Group1","Description1","Sam"
"Group1","Description1","Fred"
"Group2","Description2","Bob"
Stuff like that, right?

CuriousCoder42 -

Yes, that's it! I have other data where users are unique records, and this setup is supposed to match a one-to-many relationship.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.