2017-07-14 38 views
0

我正在尝试创建一个脚本来修改配置文件的内容,将其保存并启动相关程序。该文件显然是一个XML文件,并与我创建的脚本我把它保存在一个正常的文本文件。这可能是我的程序无法启动的原因。那么我怎样才能保存在XML?使用powershell打开并保存xml配置文件

下面是脚本:

$content = [XML](Get-Content("path\file.config")) 
$content = $content.replace("IP address","Other IP address") 
$content | out-file "path\file.config" 

在此先感谢

+3

第一关:**请不要在XML使用正则表达式**。你的脚本没有任何明显的错误。你可以显示'file.config'的内容吗? –

+0

@ MathiasR.Jessen我同意这种观点;请记住['.Replace'是字符串替换,而'-replace'是正则表达式替换](https://stackoverflow.com/questions/10184156/whats-the-difference-between-replace-and-replace-in-powershell ) – gms0ulman

+0

大家好,我用@slong16解决方案,它工作得很好。谢谢 – RazZ

回答

0
$content = Get-Content "path\file.config" | Out-String 
$content = $content.replace("IP address","Other IP address") 
$content = ([xml]$content).save("path\file.config") 
+0

感谢这工作,因为我需要它的工作=) – RazZ

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" 
+0

你好,谢谢你的帮助,但我没有设法使它工作...我是PS的noob,所以它可能是我的错。谢谢反正=) – RazZ