首页 > 解决方案 > 使用 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 文件中。

标签: xmlpowershellnodes

解决方案


所以我需要改变

$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>
"@

推荐阅读