Powershell - 如何将<sectiongroup>添加到web.config </sectiongroup>

时间:2013-06-16 16:48:25

标签: powershell web-config configsection

我正在尝试使用Powershell向web.config中的sectionGroup元素添加configuration/configSections元素。

我目前有

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

# navigate to the <configSections> element
$xmlConfigSections = $xml.SelectSingleNode("//configuration/configSections")

# create the new <sectionGroup> element with a 'name' attribute
$sectionGroup = $xml.CreateElement("sectionGroup")
$xmlAttr = $xml.CreateAttribute("name")
$xmlAttr.Value = "myCustomSectionGroup"
$sectionGroup.Attributes.Append($xmlAttr)

# now add the new <sectionGroup> element to the <configSections> element
$xmlConfigSections.AppendChild($sectionGroup)

#save the web.config
$xml.Save($filePath)

但这会导致CreateElement方法出现异常:

  

“无法插入指定的节点作为此的有效子节点   node,因为指定的节点类型错误。“

我不明白为什么当我尝试创建元素时抛出这样的异常(异常似乎与附加元素有关)。

我尝试过的其他东西是

$newConfig = [xml]@'<sectionGroup name="myCustomSectionGroup"></sectionGroup>'@

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

# navigate to the <configSections> element
$xmlConfigSections = $xml.SelectSingleNode("//configuration/configSections")

$xmlConfigSections.AppendChild($newConfig)

但这会抛出与以前完全相同的异常。

<sectionGroup>绝对是<configSections>的有效孩子。

理想情况下,我更喜欢第二次尝试是否有效,因为这不需要我声明每个元素,每个属性,

有人可以向我解释为什么<configSections>节点不允许我的<sectionGroup>元素吗?

1 个答案:

答案 0 :(得分:6)

这应该这样做:

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

$sectionGroup = $xml.CreateElement('sectionGroup')
$sectionGroup.SetAttribute('name','myCustomSectionGroup')
$sectionGroupChild = $xml.CreateElement('sectionGroupChild')
$sectionGroupChild.SetAttribute('name','myCustomSectionGroup')

$newNode = $xml.configuration.configSections.AppendChild($sectionGroup)
$newNode.AppendChild($sectionGroupChild)

$xml.Save($filePath)