xml - 使用 PowerShell 在 XML 中添加新的子节点
问题描述
我支持基于 Web 的应用程序,当升级到最新版本时,有些配置无法正确更新。这将在下一个版本中修复,但同时我们需要向少数 XML 文件添加一些信息。为了消除人为错误的机会,我希望为此编写一个 Powershell 脚本,但我遇到了一些麻烦......
所以我有一个包含以下信息的 XML 文件:
<configuration>
<configSections>
<appSettings>
<system.web>
<system.webServer>
<httpRedirect enabled="false" />
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
<httpProtocol>
<customHeaders>
<add name="HeaderName" value="HeaderValue" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
我需要将以下信息添加到 system.webServer 部分的顶部:
<handlers>
<add name="NAME1" preCondition="Precondition" type="Type" path="Path" verb="*"/>
<add name="NAME2" preCondition="Precondition" type="Type" path="Path" verb="*"/>
</handlers>
到目前为止,我得到的是:
#Declare variable for file path
$Path = "C:\Folder\File.xml"
#Declare variable to view path as XML
[XML]$File = gc $Path
#Variable for Node
$Node = $File.configuration."system.webServer"
$Variable for newNode
$newNode = @"
<handlers>
<add name="NAME1" preCondition="Precondition" type="Type" path="Path" verb="*"/>
<add name="NAME2" preCondition="Precondition" type="Type" path="Path" verb="*"/>
</handlers>
"@
#Add $newNode to system.webServer section of File.xml file just before httpRedirect section
$Node.InsertBefore($File.ImportNode($newNode.handlers, $true), $Node.httpRedirect) | out-Null
#Save the file
$File.Save($Path)
但是当我运行它时,我得到了错误:
Exception calling "ImportNode" with "2" argument(s): "Cannot import a null node."
我正在努力弄清楚我可能做错了什么,并且很好奇是否有人能够指出我正确的方向。我过去做过一些 XML 操作,但主要是更改值。我以前从未添加到 XML 文件中。
解决方案
所以我需要改变
$newNode = @"
<handlers>
<add name="NAME1" preCondition="Precondition" type="Type" path="Path" verb="*"/>
<add name="NAME2" preCondition="Precondition" type="Type" path="Path" verb="*"/>
</handlers>
"@
至
$newNode = [XML]@"
<handlers>
<add name="NAME1" preCondition="Precondition" type="Type" path="Path" verb="*"/>
<add name="NAME2" preCondition="Precondition" type="Type" path="Path" verb="*"/>
</handlers>
"@
推荐阅读
- command-line-interface - 尝试在 Github Action 中解析 JSON 输出
- c++ - 文件输入/输出和 std::string 问题
- reactjs - 使用 mobx 时刷新浏览器并移动页面时如何保留该值?
- python - 如何去除seaborn线图的背景
- android - Flutter Geolocator 5.0.1 无法正常工作
- python - Apache Beam 不会针对 google 数据流上的会话窗口提前重复触发
- java - 避免 QProcess 被杀死 (QProcess: Destroyed while process is still running)
- algorithm - 有向树变异算法
- xampp - xampp 在 ubuntu 中安装但 php 和 mysql 显示未找到
- html - 使用 pd.read_html 从网页导入表格