请帮我创建一个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>
答案 0 :(得分:22)
你有两个解决方案。您可以将其读作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")
或者你可以使用简单的字符串替换更简单,更快速,就像它是普通的文本文件一样。我会推荐这个。例如:
#using simple text replacement
$con = Get-Content .\test.xml
$con | % { $_.Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar") } | Set-Content .\test.xml
答案 1 :(得分:14)
我知道这是一个老帖子,但这可能对其他人有帮助......
如果您明确知道要查找的元素,那么您只需指定元素:
# 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")
答案 2 :(得分:1)
试试这个:
$xmlFileName = "c:\so.xml"
$match = "C:\\Prog\\Laun\.jar"
$replace = "C:\Prog32\folder\test.jar"
# Create a XML document
[xml]$xmlDoc = New-Object system.Xml.XmlDocument
# Read the existing file
[xml]$xmlDoc = Get-Content $xmlFileName
$buttons = $xmlDoc.config.button
$buttons | % {
"Processing: " + $_.name + " : " + $_.command
$_.command = $_.command -Replace $match, $replace
"Now: " + $_.command
}
"Complete, saving"
$xmlDoc.Save($xmlFileName)