powershellweb-configconfigsection

Powershell - how to add <sectionGroup> to web.config


I'm trying to add a sectionGroup element to the configuration/configSections element in a web.config using Powershell.

I currently have

$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)

But this incurs an exception on the CreateElement method:

"The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."

I don't understand why such an exception is being thrown when I try to create the element (the exception appears to relate to appending an element).

Something else I've tried is

$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)

But this throws the exact same exception as previously.

<sectionGroup> is definitely a valid child of <configSections>.

Ideally, I'd prefer if the second attempt worked because this doesn't require me to declare every element, every attribute, etc.

Can someone please explain to me why the <configSections> node isn't allowing my <sectionGroup> element?


Solution

  • This should do it:

    $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)