xml - Powershell-XML在现有部分中插入新行

标签 xml powershell

我已经解压缩了XML文件的默认安装,该文件预先装有XML设置,例如...

<system.web>
  <compilation targetFramework="4.6.1" debug="false" />
  <httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters=""/>
</system.web>

我在每个发行版上都会进行一系列环境更改,因此它在system.web部分增加了一行。
<system.web>
  <compilation targetFramework="4.6.1" debug="false" />
  <httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters=""/>
  <customErrors mode="Off" />
</system.web>

我将在Octopus部署中使用它,我相信它以Powershell 2.0为基础。

在Powershell脚本中,如何添加...
customErrors mode =“Off” /
...声明到该XML文件的现有system.web部分?

提前致谢
(先前链接的重复问题不是一个简洁的答案-谢谢)

最佳答案

经过大量的反复试验,发现它...

我之前的XML ...

<?xml version="1.0"?>
<configuration>
  <anothernode>
     <notalot target="1" debug="dish" />
  </anothernode>
  <system.web>
     <compilation targetFramework="4.6.1" debug="false" />
     <httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters="" />
  </system.web>
</configuration>

Powershell代码,我选择改用$ var值,但是没有什么阻止您将硬编码的东西放入代码中,但请记住它们周围的''引号!
# This will add <customErrors mode="Off" /> to the system.web section
$filename = "C:\Users\user\Desktop\Neil\newxmlsettings.xml"
$var1 = 'customErrors'
$var2 = 'mode'
$var3 = 'Off'
#
[xml]$xml = Get-Content $filename
$body = [xml]$xml
$newnode = $body.CreateElement($var1)
$newnode.SetAttribute($var2,$var3)
$body.SelectSingleNode("//system.web").AppendChild($newnode)
$xml.Save($filename)

仅需要AppendChild语句中带引号的“system.web”,因为它有一个。其中,对于单元素名称,您可以省略其双引号。

最终XML ...
<?xml version="1.0"?>
<configuration>
  <anothernode>
     <notalot target="1" debug="dish" />
  </anothernode>
  <system.web>
     <compilation targetFramework="4.6.1" debug="false" />
     <httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters="" />
     <customErrors mode="Off" />
  </system.web>
</configuration>

关于xml - Powershell-XML在现有部分中插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527385/

相关文章:

c# - 使用 PowerShell 查找最接近的 System.Color 实例

powershell - Find-Package没有-ScriptSourceLocation参数

powershell - 对为什么必须在Windows上安装PowerShell Core感到困惑...?

javascript - 我怎样才能只得到第一层的元素?

c# - 带有 XmlTypeMapping 和 XmlRootAttribute 参数的 XmlSerializer 构造函数

xml - 将 XPath count() 与 contains() 一起使用

xml - XPath 中//*/和/*//之间的区别?

python - 查找 XML 标记值并选择包含所请求标记值的父级

PowerShell -gt 比较运算符不起作用

php - 如何在 PHP 中运行 Powershell 脚本?