41

请帮助我创建一个将通过 XML 文件并更新内容的 Powershell 脚本。在下面的示例中,我想使用脚本来拉出并更改 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>
4

3 回答 3

54

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

如果您特别了解要查找的元素,则可以简单地指定元素,如下所示:

# 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")
于 2017-03-09T16:01:55.347 回答
44

你有两个解决方案。您可以将其读取为 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
于 2013-05-07T21:47:57.493 回答
2

尝试这个:

$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)
于 2013-05-07T21:49:40.077 回答