如何使用 powershell 在 web.config 中的 <configSections> 中添加新的 <section>

How to add new <section> inside <configSections> in web.config using powershell

我想在 configSections 标签中添加新的部分元素

<configuration>
<configSections>
<sectionGroup name="SharePoint">
  <section name="SafeControls" type="Microsoft.SharePoint.ApplicationRuntime.SafeControlsConfigurationHandler, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
  <section name="RuntimeFilter" type="System.Configuration.SingleTagSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <section name="WebPartLimits" type="System.Configuration.SingleTagSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />      
</sectionGroup>

<section name="MySection" type="MyType" />
</configSections>

如何在 configSections 内部但在 sectionGroup 外部添加 "MySection"?

谢谢

我找到了解决方案。

$path = $("IIS:\Sites\" + $title)
$physicalPath = $(get-item "$path").physicalPath
$configpath = $($physicalPath + "\web.config");
$content = Get-Content -Path $configpath
[System.Xml.XmlDocument] $xmlDoc = new-object System.Xml.XmlDocument
$xmlDoc.LoadXml($content)
$oauthName = "oauth2.login.configuration"
$oauthSectionNode = $xmlDoc.selectSingleNode("/configuration/configSections/section[@name='$oauthName']")

if(!$oauthSectionNode)
{
    $mainNode = $xmlDoc.selectSingleNode("/configuration/configSections")
    $oauthSectionNode = $xmlDoc.CreateNode("element","section","")

    $oauthAttr = $xmlDoc.CreateAttribute("name")
    $oauthAttr.Value = "MySection"
    $oauthSectionNode.Attributes.Append($oauthAttr)

    $oauthTypeAttr = $xmlDoc.CreateAttribute("type")
    $oauthTypeAttr.Value = "MyType"
    $oauthSectionNode.Attributes.Append($oauthTypeAttr)

    $mainNode.AppendChild($oauthSectionNode)
    $xmlDoc.Save($configpath) 
}