2017-07-14 83 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