I am trying to convert a CSV document into an XML document for import into a directory. The CSV is formatted as follows:
Firstname,Lastname,Email,Phone,Room,ID
Bob,Smith,Bobs@email.com,1111,Suite 101,1
John,Doe,John@email.com,2222,Suite 102,2
The desired XML output needs to be as follows:
<?xml version="1.0" encoding="UTF-8"?>
<TSP version="1.1">
<contact firstname="Bob" lastname="Smith" email="Bobs@email.com" Phone="1111" room="Suite 101" id="1"/>
<contact firstname="John" lastname="Doe" email="John@email.com" phone="2222" room="Suite 102" id="2"/>
</TSP>
Using information from this post Powershell CSV to XML I was able to get the following output which is close but missing some bindings:
<contact Firstname ="Bob" Lastname= "Smith Email= "Bobs@email.com Phone= "1111" Room= "Suite 101" Phone= "1111" />
<contact Firstname ="John" Lastname= "Doe Email= "John@email.com Phone= "2222" Room= "Suite 102" Phone= "2222" />
Any help is very much appreciated!
Script Used:
$docTemplate = @'
<contact $($contacts -join "`n") />
'@
$entryTemplate = @'
Firstname ="$($Phone.Firstname)" Lastname= "$($Phone.Lastname) Email= "$($Phone.Email) Phone= "$($Phone.Phone)" Room= "$($Phone.Room)" Phone= "$($Phone.Phone)"
'@
Import-Csv Test.csv -Delimiter ',' | Group-Object Id -ov grp | ForEach-Object {
$contacts = foreach ($Phone in $_.Group) {
$ExecutionContext.InvokeCommand.ExpandString($entryTemplate)
}
$ExecutionContext.InvokeCommand.ExpandString($docTemplate) } |
Set-Content -LiteralPath file.xml