注意:我使用ConvertTo-XML,不能使用Export-Clixml:
我创建一个简单的PSObject:
$a = New-Object PSObject -Property @{ Name='New' Server = $null Database = $null UserName = $null Password = $null }
然后我使用ConvertTo-XML将其转换为XML:
$b = $a | Convertto-XML -NoTypeInformation
XML如下所示:
<?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>
您可以使用XPath轻松实现.尽管PowerShell通常使XML的工作非常简单,但在这种情况下,我认为使用严格PowerShell语法的格式将非常粗糙.
filter XmlProperty([String]$Property) { $_.SelectSingleNode("/Objects/Object/Property[@Name='$Property']").InnerText } $Name = $b | Xmlproperty Name $Server = $b | XmlProperty Server # etc...
编辑:一般来说,对于包含一个或多个Object元素的XML文档,您可以执行以下操作:
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