I'm trying to get some tab-delimited CSV files into an XML via PowerShell, and I'm struggling to make sense of it all. I'm 100% sure it's something really simple I'm missing, so help would be massively appreciated. I'm very close but just can't get over the final hurdle.
I essentially want this script to iterate through a tab-delimited CSV it's pointed at ($path), take each line off of the CSV and put the data into an XML sheet ($xmlpath).
CSV example:
"Name" "Item" "Purchase Price" "Jimmy Smits" "Egg" "£40" "Edward Price" "KumQuat" "£6000" "Timmy Mallet" "Bug" "£2" "Edgar Allen Poe" "Weird" "0" "2Pac Shakur" "Eggnog" ""
XML output template example:
<registration>
<Individual>
<Name></Name>
<Item></Item>
<Purchase Price></Purchase Price>
</Individual>
</registration>
And this is what I've been poking about with
$data = Import-Csv -Path $path -Delimiter "`t"
$xmlnames = $data | Select-Object "Name"
$xmlitems = $data | Select-Object "Item"
$xmlprice = $data | Select-Object "Purchase Price"
$entryTemplate = @'
<individual>
<Name>$($xmlnames.Name)</Name>
<Item>$($xmlitems.Item)</Item>
<Purchase Price>$($xmlprice."Purchase Price")</Purchase Price>
</individual>
'@
$xml = $data | ForEach-Object {
$ExecutionContext.InvokeCommand.ExpandString($entrytemplate)
}
$xml | Out-File $xmlpath
Which then puts out;
<Individual>
<Name>Jimmy Smits Edward Price Timmy Mallet Edgar Allen Poe 2Pac Shakur</Name>
<Item>System.Object IList.Item(int index) {get;set;}</Item>
<Purchase Price>£40 £6000 £2 0 </Purchase Price>
</Individual>
So somewhere I'm messing up stupidly on two things;
- The
$data | Select-Object 'thing'is giving me all of the list of 'things' rather than iterating through each of the 'things' and listing them one per XML entry. Yet is giving me the correct number of entries? - My 'Items' are being listed as system objects (not values), despite being treated identically to everything else.