如何使用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 >
**
我有一个这样的剧本,它不能正常工作
$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 :(得分:1)
您需要修复XML并使用XmlNamespaceManager
来访问文档:
$nsMgr = new-object xml.XmlNamespaceManager($doc.NameTable)
$doc.selectnodes("/ServiceConfiguration/Role/ConfigurationSettings/Setting", $nsMgr)
答案 1 :(得分:1)
这是一个如何做你想做的事情的例子。你可以写ii更短,我详细解释了一切,只是为了解释。
$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