在Windows自动化运维场景中,通过PowerShell操作XML文件是处理配置信息、数据交换文件的常用手段,读取XML属性是其中最基础也最常用的操作之一。PowerShell内置了XML解析能力,不需要额外安装组件就能完成相关操作。

PowerShell处理XML的基础方式
PowerShell中可以直接将XML字符串或XML文件转换为对象进行操作,主要有两种加载XML的方式:一种是使用Get-Content命令读取文件后转换为XML对象,另一种是使用.NET框架的System.Xml.XmlDocument类加载文件。两种方式各有适用场景,前者语法更简洁,后者支持更精细的XML操作控制。
方式一:直接转换XML文件为对象
这种方式适合结构简单的XML文件,操作语法更贴近PowerShell的原生风格,示例代码如下:
# 读取XML文件并转换为XML对象
$xmlPath = "C:testconfig.xml"
$xmlContent = Get-Content -Path $xmlPath -Encoding UTF8
$xmlObj = [xml]$xmlContent
# 假设XML结构如下:
# <configuration>
# <appSettings>
# <add key="logPath" value="C:logs" />
# <add key="maxSize" value="1024" />
# </appSettings>
# </configuration>
# 读取appSettings下第一个add节点的value属性
$firstValue = $xmlObj.configuration.appSettings.add[0].value
Write-Host "第一个add节点的value属性值:$firstValue"
# 遍历所有add节点读取key和value属性
foreach ($node in $xmlObj.configuration.appSettings.add) {
Write-Host "key: $($node.key), value: $($node.value)"
}
方式二:使用XmlDocument类加载
这种方式适合需要更严谨的XML解析场景,比如处理包含命名空间、注释的XML文件,示例代码如下:
# 创建XmlDocument对象并加载文件
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.Load("C:testconfig.xml")
# 获取目标节点
$targetNodes = $xmlDoc.SelectNodes("//add")
# 读取每个节点的属性
foreach ($node in $targetNodes) {
$keyAttr = $node.GetAttribute("key")
$valueAttr = $node.GetAttribute("value")
Write-Host "key属性:$keyAttr,value属性:$valueAttr"
}
读取带命名空间的XML属性
如果XML文件包含命名空间,直接按普通路径读取会失败,需要先注册命名空间再查询,示例代码如下:
# 带命名空间的XML示例内容:
# <root xmlns="http://www.ippipp.com/config">
# <item id="1" name="test" />
# </root>
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.Load("C:testns_config.xml")
# 创建命名空间管理器
$nsManager = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
$nsManager.AddNamespace("cfg", "http://www.ippipp.com/config")
# 使用命名空间查询节点并读取属性
$itemNodes = $xmlDoc.SelectNodes("//cfg:item", $nsManager)
foreach ($item in $itemNodes) {
$id = $item.GetAttribute("id")
$name = $item.GetAttribute("name")
Write-Host "id: $id, name: $name"
}
常见问题与注意事项
- XML文件路径包含空格时,需要给路径加上英文单引号,避免解析错误
- 读取属性前最好先判断节点是否存在,避免出现空引用错误
- 如果XML文件编码不是UTF8,需要在
Get-Content时指定正确的Encoding参数 - 使用
SelectNodes方法时,XPath表达式的语法要符合XML标准,路径错误会导致返回空结果
实际应用场景示例
比如需要读取IIS配置文件applicationHost.config中的站点绑定信息,就可以用以下代码实现:
# 读取IIS配置文件中的站点绑定端口
$iisConfigPath = "C:WindowsSystem32inetsrvconfigapplicationHost.config"
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.Load($iisConfigPath)
# 查询所有站点的绑定节点
$bindingNodes = $xmlDoc.SelectNodes("//sites/site/bindings/binding")
foreach ($binding in $bindingNodes) {
$protocol = $binding.GetAttribute("protocol")
$bindingInfo = $binding.GetAttribute("bindingInformation")
Write-Host "协议:$protocol,绑定信息:$bindingInfo"
}
PowerShellXMLWindows脚本XML属性读取修改时间:2026-07-14 03:51:21