2014-09-05 64 views
0

嗨,我試圖改變powershell中的目標值,但沒有運氣。 這是我正在使用的腳本。它可以很好地改變應用程序的設置值,但不是目標值如何使用powershell修改web.config中的目標值

$webConfig = 'C:\Users\Desktop\xml\web.config' 
$doc = (Get-Content $webConfig) -as [Xml] 
$obj = $doc.configuration.targets | where {$_.filename -eq 'test.log.txt'} 
$obj.value = 'C:\test_logs\test.log.txt-${shortdate}.log.txt' 
$doc.Save($webConfig) 

我收到以下錯誤。 無法在此對象上找到屬性「值」。驗證該屬性是否存在並可以設置。

這是在web.config

<targets> 
    <target name="f1" xsi:type="File" fileName="test.log.txt" layout="${threadname} ${longdate} 
${callsite} ${logger}[${level}] ${message}" /> 
    <target name="console" xsi:type="Console" layout="${threadname} ${longdate} ${callsite} 
${logger}[${level}] ${message}" /> 
</targets> 

編輯的腳本 $ webConfig = 'C:\用戶\桌面\ XML \的web.config' $ DOC =(獲取內容$ webConfig)-as [Xml] $ obj = $ doc.configuration.targets.target |其中{$ _。fileName -eq'test.log.txt'} $ obj.SetAttribute'C:\ test_logs \ test.log.txt - $ {shortdate} .log.txt' $ doc.Save($ webConfig )

回答

0

$ obj是空的,你錯過了 '目標' 屬性

$obj = $doc.configuration.targets | foreach { $_.target } | where { $_.fileName... 

或者在V3:

$obj = $doc.configuration.targets.target | where { $_.fileName -and $_.fileName -eq.. 
+0

我收到此錯誤消息,當我使用上面的代碼 – san 2014-09-08 13:51:46

+0

你不能調用一個空值表達式的方法。我修改了有問題的腳本 – san 2014-09-08 13:52:07

0

嘗試SetAttribute(string,string)代替。我遇到的問題與使用魔法屬性的PowerShell設置的屬性/子元素:

$obj.SetAttribute('value', 'C:\test_logs\test.log.txt-${shortdate}.log.txt') 

這也將工作,如果value屬性丟失。

+0

這不適用於我 – san 2014-09-09 15:52:19