Note: I'm using ConvertTo-XML
and cannot use Export-Clixml
:
I create a simple PSObjec
t:
$a = New-Object PSObject -Property @{ Name='New' Server = $null Database = $null UserName = $null Password = $null }
I then convert it into XML using ConvertTo-XML
:
$b = $a | Convertto-XML -NoTypeInformation
The XML looks like this:
<?xml version="1.0"?> <Objects> <Object> <Property Name="Password" /> <Property Name="Name">New</Property> <Property Name="Server" /> <Property Name="UserName" /> <Property Name="Database" /> </Object> </Objects>
I'm having trouble figuring out the dot notation or XPath query to extract the attributes/elements and convert $b
back to the original PSObject
.
Casting XML Strings to Objects Another way to use PowerShell to parse XML is to convert that XML to objects. The easiest way to do this is with the [xml] type accelerator. By prefixing the variable names with [xml] , PowerShell converts the original plain text XML into objects you can then work with.
To convert the XML file to a CSV file, we need to traverse it to XML child nodes and pass it as input to the Export-CSV command in PowerShell. Export-CSV command takes XML nodes as input to create a CSV file from the XML child nodes and export them to a CSV file with a delimiter comma.
One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.
Using XML files is very common in the IT World and PowerShell gives us a possibility to manipulate XML files. To export XML file in PowerShell we use Export-Clixml CmdLet likewise to import the XML file in PowerShell we use Import-Clixml CmdLet but in this article, we will focus on exporting XML files.
You can do this pretty easily with XPath. Although PowerShell usually makes working with XML pretty simple, in this case I think the format using strictly PowerShell syntax would be pretty gross.
filter XmlProperty([String]$Property) { $_.SelectSingleNode("/Objects/Object/Property[@Name='$Property']").InnerText } $Name = $b | Xmlproperty Name $Server = $b | XmlProperty Server # etc...
EDIT: To generically do this for an XML document that contains one or more Object elements, you can do something like this:
function ConvertFrom-Xml($XML) { foreach ($Object in @($XML.Objects.Object)) { $PSObject = New-Object PSObject foreach ($Property in @($Object.Property)) { $PSObject | Add-Member NoteProperty $Property.Name $Property.InnerText } $PSObject } } ConvertFrom-Xml $b
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