2011-04-11 84 views
1

'設置' name屬性值如何更改使用PowerShell腳本如何更改使用PowerShell腳本

XML

**

<ServiceConfiguration serviceName="test" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"> 
    <Role name="Role1"> 
    <Instances count="1" /> 
    <ConfigurationSettings> 
     <Setting name="enableCounter" value="true" /> 
    </ConfigurationSettings> 
    </Role> 
    <Role name="Role2"> 
    <Instances count="1" /> 
    <ConfigurationSettings> 
     <Setting name="enableCounter" value="true" /> 
    </ConfigurationSettings> 
    </Role> 
</ServiceConfiguration > 
'設置' name屬性值

**

我有這樣的腳本,它不工作

$serviceconfigpath= "D:\ServiceConfiguration.cscfg" 
$doc = new-object System.Xml.XmlDocument 
$doc.Load($serviceconfigpath) 

$testValue= "test" 

foreach($n in $doc.selectnodes("/ServiceConfiguration/Role")) 
{ 
    foreach($n in $doc.selectnode("/ServiceConfiguration/Role/ConfigurationSettings/Setting")) 
    { 
     switch($n.name) 
     { 
      "enableCounter" { $n.value = $testValue} 
     } 
    } 
} 

$doc.Save($serviceconfigpath) 
+0

你的XML被打破。缺少''標籤。 – vonPryz 2011-04-11 08:26:43

+0

現在正固定 – SRA 2011-04-11 08:49:07

回答

1

你需要修復的XML和使用XmlNamespaceManager訪問該文檔:

$nsMgr = new-object xml.XmlNamespaceManager($doc.NameTable) 
$doc.selectnodes("/ServiceConfiguration/Role/ConfigurationSettings/Setting", $nsMgr) 
+0

現在正固定。我可以知道你對此的評論嗎? – SRA 2011-04-11 08:49:48

1

這裏是你如何能做到你想要的一個例子。你可以寫得更短,我詳細說明了一切,只是爲了解釋。

$testValue= "test" 

# Read the XML file 
$file = Get-Content "c:\temp\FileBefore.xml" 

# See it as an XMLDocument 
$xml = [xml] $file 

foreach ($role in $xml.ServiceConfiguration.role) 
{ 
    # name before 
    $role.ConfigurationSettings.Setting.name 
    # modification 
    $role.ConfigurationSettings.Setting.name = $testValue 
    # name after 
    $role.ConfigurationSettings.Setting.name 
} 

# Save it back to a file 
$xml.Save("c:\temp\FileAfter.xml") 

JP

+0

它不工作我的cscfg文件是windows azure雲服務的服務配置。非常感謝。 – SRA 2011-04-12 06:49:57

+0

對不起,Sunil,如果你複製/過去的XML你給我們它的作品。您當然需要適應您的XML或提供最終文件。 – JPBlanc 2011-04-12 09:19:25

相關問題