2014-09-05 122 views
0

我對PowerShell相對來說比較陌生,而且我在使用PowerShell創建腳本來修改和保存XML文件(web.config)時遇到了問題。 XML文件的結構如下:使用PowerShell編輯和保存XML文件時遇到問題

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <appSettings> 
     <add key="Password" value="Test1234" /> 
    </appSettings> 
</configuration> 

我試圖在試圖讓PowerShell來修改密碼值,並再次保存,但不正在許多方法。我的最新存檔:

$webConfig = "Z:\TEMP\Web.config" 
$doc = new-object System.Xml.XmlDocument 
$doc.Load($webConfig) 
$doc.get_DocumentElement()."appSettings".WebAdminPassword.value = "$Password" 
$doc.Save($webConfig) 

變量$ Password是一個隨機生成的15個字符的密碼,它在腳本的早期生成。任何人都可以告訴我哪裏出錯了?謝謝!

回答

1

試試這個:

$xml = [xml]@' 
<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <appSettings> 
     <add key="Password" value="Test1234" /> 
    </appSettings> 
</configuration> 
'@ 

$xml.configuration.appSettings.add | Where {$_.Key -eq 'password'} | 
            Foreach {$_.value = 'newpassword'} 
$xml.Save() 

據我所看到的,沒有元素或屬性命名WebAdminPassword。

+0

非常好謝謝你,你解決了我的問題!沒有任何屬性WebAdminPassword來自我正在嘗試編輯的其他文件。謝謝你的幫助 – 4dogsofwar 2014-09-05 16:23:51

相關問題