首页 > 解决方案 > 使用基于属性名称的 Powershell 更新 XML 设置

问题描述

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <SystemConfig>
    <Setting name="Email---SmtpDebug">false</Setting>
    <Setting name="Setting-Email">true</Setting>
    <Setting name="Program--Debug--Application">false</Setting>
 </SystemConfig>

以上述 XML 文件为例,在 PowerShell 中,我想通过属性名称查找设置并更新 XML 文件中的布尔值。

例如,如果我们需要打开 smtp 调试,通过属性 name=""Email---SmtpDebug" 找到设置,然后将布尔值更改为 false。

任何帮助表示赞赏。我是 Powershell 的新手。

谢谢你

标签: xmlpowershellattributes

解决方案


另一种没有 XPath 的方法是这样的:

[xml]$x = @'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <SystemConfig>
    <Setting name="Email---SmtpDebug">false</Setting>
    <Setting name="Setting-Email">true</Setting>
    <Setting name="Program--Debug--Application">false</Setting>
 </SystemConfig>
'@
$e = $x.SystemConfig.Setting | ? {$_.name -eq "Email---SmtpDebug"} 
$e."#text" = "true"
$x.save([console]::out)
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<SystemConfig>
  <Setting name="Email---SmtpDebug">true</Setting>
  <Setting name="Setting-Email">true</Setting>
  <Setting name="Program--Debug--Application">false</Setting>
</SystemConfig>

推荐阅读