首页 > 解决方案 > 用于更新 XML 文件的 Powershell 脚本

问题描述

有什么方法可以使用 PowerShell 更新我的 XML 文件:

我当前的文件格式:

   <?xml version="1.0"?>
   <Configuration>
     <SPaths>
        <path>Share</path>
     </SPaths>

我的输出应该是:

   <?xml version="1.0"?>
   <Configuration>
     <SPaths>
        <path>My Share</path>
        <path>My Share/xyz</path>
        <path>My Share/abc</path>
     </SPaths>

我正在使用以下命令

   $myXML = [xml](Get-Content 'C:\MyPath.config')
   $myXML.Configuration.SPaths.path = "My Share"
   $myXML.Save("C:\MyPath.config")

我需要再添加 2 行代码,非常感谢任何帮助,谢谢。

标签: xmlpowershell

解决方案


使用下面给出的命令,我可以在我的 XML 文件中添加新行。谢谢丹尼尔

$myXML.Configuration.SPaths.path = "My Share"
$xmlElt = $myXML.CreateElement("path")
$xmlText = $myXML.CreateTextNode("My Share/xyz")
$xmlElt.AppendChild($xmlText)
$myXML.Configuration.SPaths.InsertBefore($xmlElt, $myXML.Configuration.SPaths.legacyUnhandledExceptionPolicy)
$xmlElt1 = $myXML.CreateElement("path")
$xmlText1 = $myXML.CreateTextNode("My Share/abc")
$xmlElt1.AppendChild($xmlText1)
$myXML.Configuration.SPaths.InsertBefore($xmlElt1, $myXML.Configuration.SPaths.legacyUnhandledExceptionPolicy)
$myXML.Save("C:\MyPath.config")```

推荐阅读