[英]Powershell script to update XML file content
請幫助我創建一個 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>
我知道這是一個舊帖子,但這可能對其他人有幫助,所以......
如果您特別了解要查找的元素,則可以簡單地指定元素,如下所示:
# 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")
你有兩個解決方案。 您可以將其讀取為 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
試試這個:
$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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.