tags:

views:

60

answers:

1

Note: I'm using ConvertTo-XML and cannot use Export-Clixml:

I create a simple PSObject:

$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.

+3  A: 

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
Josh Einstein
Thanks Josh. I Would like to convert any PSObject, but this is enough to get me started. I'm doing this because PSObject doesn't support .NET serialization.
Chad Miller
I updated my answer with a more general way of going back to PSObject. However, it's not recursive so keep that in mind.
Josh Einstein
Nice! Thanks again.
Chad Miller