【问题标题】:Powershell script to update XML file content用于更新 XML 文件内容的 Powershell 脚本
【发布时间】:2013-05-01 23:14:19
【问题描述】:

请帮助我创建一个将通过 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>

【问题讨论】:

标签: xml file powershell


【解决方案1】:

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

如果您明确知道要查找的元素,则可以简单地指定元素,如下所示:

# 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】:

您有两种解决方案。您可以将其读取为 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

【讨论】:

  • 请注意,$xml.SelectNotes 中的 //"command" 区分大小写,例如它在 .xml 文件中的显示方式。
【解决方案3】:

试试这个:

$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)

【讨论】:

  • 难道你不应该也逃避$match 中的. 吗?此外,您可以将创建和读取 xml 部分与简单的演员相结合。 :-)
  • 是的,您在 .比赛,谢谢你指出这一点。如果 xml 文件不存在,我经常将我的创建和读取分开,因为我经常从头开始构建 xml。在这种情况下并非如此,但这是我已经习惯的模式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
相关资源
最近更新 更多