当您决定使用 XML 作为数据格式时,您会发现内置的 Export/Import-CliXml cmdlet 是将 您自己的对象 保存到 XML 文件和反向操作的简单方法。但是如果您需要处理来自您自己未创建的源的 XML 数据,该怎么办呢?让我们来看一下名为“Xml”的 cmdlet:ConvertTo-Xml。它可以将任何对象转换为 XML 格式:
1 2 3 4 5
PS> Get-Process-Id$pid | ConvertTo-Xml
xml Objects ---------- version="1.0" encoding="utf-8" Objects
# data to be persisted in XML: $Data = Get-Process | Select-Object-First10# let's take 10 random processes, # can be any data # destination path for XML file: $Path = "$env:temp\result.xml"
# take original data $Data | # convert each item into an XML object but limit to 2 levels deep ConvertTo-Xml-Depth2 | # pass the string XML representation which is found in property # OuterXml Select-Object-ExpandProperty OuterXml | # save to plain text file with appropriate encoding Set-Content-Path$Path-Encoding UTF8
# path to XML file: $Path = "$env:temp\result.xml"
# read file and convert to XML: [xml]$xml = Get-Content-Path$Path-Raw-Encoding UTF8
# dive into the XML object model (which happens to start # in this case with root properties named "Objects", then # "Object": $xml.Objects.Object | # next, examine each object found here: ForEach-Object { # each object describes all serialized properties # in the form of an array of objects with properties # "Name" (property name), "Type" (used data type), # and "#text" (property value). # One simple way of finding a specific entry # in this array is to use .Where{}: $Name = $_.Property.Where{$_.Name -eq'Name'}.'#text' $Id = $_.Property.Where{$_.Name -eq'Id'}.'#text' $_.Property | Out-GridView-Title"Process $Name (ID $Id)" }