我正在尝试创建一个脚本来修改配置文件的内容,保存并启动相关程序。该文件显然是一个xml文件,并且使用我创建的脚本将其保存在普通文本文件中。这可能是我的程序不再启动的原因。那么如何保存xml?
这是脚本:
$content = [XML](Get-Content("path\file.config"))
$content = $content.replace("IP address","Other IP address")
$content | out-file "path\file.config"
提前致谢
本
答案 0 :(得分:0)
这段代码没有意义,因为它部分处理xml
而部分处理文本。我试图通过下面的评论来说明这一点,以及如何解决这个问题。
示例输入
<?xml version="1.0"?>
<mytag>IP address</mytag>
<强>击穿强>
# this line imports the file, and turns it into an XML object. so far so good.
$content = [XML](Get-Content("path\file.config"))
# this line leads to an error:
# Method invocation failed because [System.Xml.XmlDocument] does not contain a method named 'replace'
$content = $content.replace("IP address","Other IP address")
# this line will try to export the xml object (unsuccessfully)
$content | out-file "path\file.config"
方法1 - 视为文本
$content = (Get-Content("path\file.config"))
$content = $content.replace("IP address","Other IP address")
$content | out-file "path\file.config"
方法2 - 视为xml
$content = [XML](Get-Content("path\file.config"))
$content = $content.mytag = "Other IP Address"
$content.OuterXml | out-file "path\file.config"
答案 1 :(得分:0)
$content = Get-Content "path\file.config" | Out-String
$content = $content.replace("IP address","Other IP address")
$content = ([xml]$content).save("path\file.config")