這個代碼是沒有意義的,因爲它是部分處理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"
第一關:**請不要在XML使用正則表達式**。你的腳本沒有任何明顯的錯誤。你可以顯示'file.config'的內容嗎? –
@ MathiasR.Jessen我同意這種觀點;請記住['.Replace'是字符串替換,而'-replace'是正則表達式替換](https://stackoverflow.com/questions/10184156/whats-the-difference-between-replace-and-replace-in-powershell ) – gms0ulman
大家好,我用@slong16解決方案,它工作得很好。謝謝 – RazZ