用于更新XML文件内容的Powershell脚本

use*_*932 27 xml powershell file

请帮我创建一个Powershell脚本,该脚本将通过XML文件并更新内容.在下面的示例中,我想使用该脚本在Config.button.command示例中提取并更改文件路径.将C:\ Prog\Laun.jar更改为C:\ Prog32\folder\test.jar.请帮忙.谢谢.

<config>
 <button>
  <name>Spring</name>
  <command>
     C:\sy32\java.exe -jar "C:\Prog\Laun.jar" YAHOO.COM --type SPNG --port 80
  </command>
  <desc>studies</desc>
 </button>
 <button>
  <name>JET</name>
    <command>
       C:\sy32\java.exe -jar "C:\Prog\Laun.jar" YAHOO.COM --type JET --port 80
    </command>
  <desc>school</desc>
 </button>
</config>
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 31

你有两个解决方案.您可以将其读作xml并替换文本,如下所示:

#using xml
$xml = [xml](Get-Content .\test.xml)
$xml.SelectNodes("//command") | % { 
    $_."#text" = $_."#text".Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar") 
    }

$xml.Save("C:\Users\graimer\Desktop\test.xml")
Run Code Online (Sandbox Code Playgroud)

或者你可以使用简单的字符串替换更简单,更快速,就像它是普通的文本文件一样.我会推荐这个.例如:

#using simple text replacement
$con = Get-Content .\test.xml
$con | % { $_.Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar") } | Set-Content .\test.xml
Run Code Online (Sandbox Code Playgroud)


Thi*_*Dev 26

我知道这是一个老帖子,但这可能对其他人有帮助......

如果你特别知道你正在寻找的元素,那么你可以简单地指定元素,如下所示:

# Read the existing file
[xml]$xmlDoc = Get-Content $xmlFileName

# If it was one specific element you can just do like so:
$xmlDoc.config.button.command = "C:\Prog32\folder\test.jar"
# however this wont work since there are multiple elements

# Since there are multiple elements that need to be 
# changed use a foreach loop
foreach ($element in $xmlDoc.config.button)
{
    $element.command = "C:\Prog32\folder\test.jar"
}

# Then you can save that back to the xml file
$xmlDoc.Save("c:\savelocation.xml")
Run Code Online (Sandbox Code Playgroud)