如何在PowerShell中从复杂XML生成计算机名-IP映射对象
PowerShell 从复杂XML提取计算机名与IP并生成对象
核心实现思路
- 加载XML数据并定位所有包含计算机名(cn)和IP的节点
- 遍历节点,将每个节点的信息封装为
[PSCustomObject] - 确保遍历所有匹配节点而非仅第一个
通用代码示例
情况1:XML节点包含子元素(如cn、IPAddress)
假设XML结构如下:
<NetworkInventory> <Locations> <Location name="HQ"> <Devices> <Device> <cn>DESKTOP-LK456</cn> <IPAddress>10.0.0.20</IPAddress> </Device> <Device> <cn>SERVER-MN789</cn> <IPAddress>10.0.0.100</IPAddress> </Device> </Devices> </Location> </Locations> </NetworkInventory>
处理脚本:
# 加载XML文件(若为字符串则用 [xml]$xml = $yourXmlString) $xml = [xml](Get-Content -Path "C:\inventory.xml") # 用XPath定位所有目标节点(根据你的XML结构调整路径) $computerNodes = $xml.SelectNodes("//Device") # 遍历生成对象列表 $computerList = $computerNodes | ForEach-Object { [PSCustomObject]@{ ComputerName = $_.cn.InnerText IPAddress = $_.IPAddress.InnerText } } # 查看结果 $computerList
情况2:XML节点用属性存储cn和IP
如果XML结构是属性形式:
<Network> <Machines> <Machine cn="LAPTOP-QR123" ip="192.168.1.5"/> <Machine cn="PRINTER-ST456" ip="192.168.1.20"/> </Machines> </Network>
调整脚本提取属性:
$xml = [xml](Get-Content -Path "C:\machines.xml") $computerNodes = $xml.SelectNodes("//Machine") $computerList = $computerNodes | ForEach-Object { [PSCustomObject]@{ ComputerName = $_.GetAttribute("cn") IPAddress = $_.GetAttribute("ip") } } $computerList
解决「仅输出一条」问题的关键
- 避免直接访问单个节点:比如
$xml.Network.Machines.Machine仅返回第一个节点,需用SelectNodes()或遍历数组 - 确保XPath路径正确:用
//前缀匹配所有层级的目标节点,而非仅特定层级 - 若XML含命名空间,需先注册命名空间后再使用XPath:
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable) $ns.AddNamespace("ns", "http://your-namespace-uri") $computerNodes = $xml.SelectNodes("//ns:Device", $ns)
简洁写法(一步到位)
[xml]$xml = Get-Content "C:\inventory.xml" $xml.SelectNodes("//Device") | ForEach-Object { [PSCustomObject]@{ ComputerName = $_.cn IPAddress = $_.IPAddress } }
内容的提问来源于stack exchange,提问作者Hiddai
相关产品推荐
相关产品推荐

