用于更新 XML 文件的 Powershell 脚本

时间:2021-02-22 04:19:59

标签: 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 行代码,非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

使用下面给出的命令,我可以在我的 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")```
相关问题