I am creating a new object in PowerShell, using a hash table to set property values. I want to then export the object into XML format using the ConvertTo-XML method.
$hash = @{
Processor = 'Intel'
Disk = '500GB'
Server = 'ABC'
Serial = '01234'
}
$specs = New-Object PSObject -Property $hash
Write-Output ($specs | ConvertTo-XML -notypeinformation).Save("C:\scripts\export.xml")
The XML output is as follows:
<Objects>
<Object>
<Property Name="Serial">a1b2c3</Property>
<Property Name="Server">ABC</Property>
<Property Name="Processor">Intel</Property>
<Property Name="Disk">500GB</Property>
</Object>
</Objects>
What I want, is for the XML tags to be formatted in the following way:
<Objects>
<Object>
<Serial>a1b2c3</Serial>
<Server>ABC</Server>
<Processor>Intel</Processor>
<Disk>500GB</Disk>
</Object>
</Objects>
And then, if there is a good solution for that, is there also a way to make the Object(s) tags custom as well?
Thank you.
I don't think you can get there with ConvertTo-Xml
. However, you can use here strings
to do this. It is kind of low tech but still pretty cool:
$hash = @{
Processor = 'Intel'
Disk = '500GB'
Server = 'ABC'
Serial = '01234'
}
@"
<Objects>
<Object>$(foreach ($kvpair in $hash.GetEnumerator()) {
"`n <$($kvpair.Key)>$($kvpair.Value)</$($kvpair.Key)>"
})
</Object>
</Objects>
"@ > C:\scripts\export.xml
You could use the XML DOM
to create this document but that would be more work and for such a simple document I think the here string
approach works pretty well. It is also good for any sort of text templating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With