Convert XML to PSObject

后端 未结 3 1068
半阙折子戏
半阙折子戏 2020-12-28 15:12

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

I create a simple PSObject:

$a = New-Object PSObj         


        
3条回答
  •  不知归路
    2020-12-28 15:47

    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
    

提交回复
热议问题