Add web.config Modification with PowerShell (SPWebConfigModification)

Here is a script I used to add some web.config modifications with PowerShell. In this case I want to add a custom authentication provider. – The following script I used for setup purpose.

# Load SharePoint PowerShell PSSnapIn and the main SharePoint .net library
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$sharePointDLL = $ENV:CommonProgramFiles+("Microsoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.dll")
[System.Reflection.Assembly]::LoadFile($sharePointDLL) | out-null

# Show Farm BuildVersion to ensure the SharePoint .net library is loaded
$localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$localFarm.BuildVersion

# store some settings and objects in variables
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($url)
$farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" } )[0]
$assembly = "MyAuthenticationProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxx"

# Remove old web.config modifications of MyAuthenticationProvider
$oldMods = @();
$webapp.WebConfigModifications | where-object { $_.Owner -eq "MyAuthenticationProvider" } | foreach-object { $oldMods = $oldMods + $_}

$oldMods | foreach-object{ $webapp.WebConfigModifications.Remove($_) }

# update the Web Application and apply all existing web.config modifications - this executes the "remove" actions from above
$webapp.Update()
$farmServices.ApplyWebConfigModifications()

# New web.config modifications for MyAuthenticationProvider
$myModification1 = new-object "Microsoft.SharePoint.Administration.SPWebConfigModification"
$myModification1.Path = "configuration/system.web/membership/providers"
$myModification1.Name = "add[@name='MyAuthenticationProvider'][@type='MyAuthenticationProvider.MyMembershipProvider, " + $assembly + "']"
$myModification1.Sequence = 0
$myModification1.Owner = "MyAuthenticationProvider"
$myModification1.Type = 0           #for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$myModification1.Value = "<add name='MyAuthenticationProvider' type='MyAuthenticationProvider.MyMembershipProvider, " + $assembly + "' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification2 = new-object "Microsoft.SharePoint.Administration.SPWebConfigModification"
$myModification2.Path = "configuration/system.web/roleManager/providers"
$myModification2.Name = "add[@name='MyAuthenticationProvider'][@type='MyAuthenticationProvider.MyRoleProvider, " + $assembly + "']"
$myModification2.Sequence = 0
$myModification2.Owner = "MyAuthenticationProvider"
$myModification2.Type = 0           #for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$myModification2.Value = "<add name='MyAuthenticationProvider' type'MyAuthenticationProvider.MyRoleProvider, " + $assembly + "' />"
$webapp.WebConfigModifications.Add($myModification2)

# Update the Web Application and apply all exisiting web.config modifications including the new from above

$webapp.Update()
$farmServices.ApplyWebConfigModifications()

Please notice my disclaimer in the right sidebar!

17 thoughts on “Add web.config Modification with PowerShell (SPWebConfigModification)

  1. Thanks this helped allot… one question, how do you add a section ? I.E.

    as it doesn’t exist initially…

    Thanks..
    Gerald

        • I also need to add a section which does not exist initially. However sectiongroups and section within those do exist but i want to add a section at configsections level.

          My code snippet is as under:

          $modLog4Net = New-Object -TypeName Microsoft.SharePoint.Administration.SPWebConfigModification

          $modLog4Net.path = “/configuration/configSections”

          $modLog4Net.type = 0

          $modLog4Net.name = “add[@name=’log4net’][@type=’log4net.Config.Log4NetConfigurationSectionHandler,” + $log4netAssembly + “‘]”

          $modLog4Net.value = “”

          $modLog4Net.owner = “SEPortal”

          $modLog4Net.sequence = 0

          $wa.WebService.WebConfigModifications.Clear()

          $wa.WebService.WebConfigModifications.Add($modLog4Net)

          However am getting the error:

          Exception calling “ApplyWebConfigModifications” with “0” argument(s): “The ‘[‘ character, hexadecimal value 0x5B, canno
          t be included in a name. Line 1, position 5393.”
          At E:Source CodeMy PS ScriptsModify Web ConfigAdd log4net Setting.ps1:46 char:43
          + $wa.WebService.ApplyWebConfigModifications <<<< ()
          + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
          + FullyQualifiedErrorId : DotNetMethodException

          $wa.WebService.Update()

          $wa.WebService.ApplyWebConfigModifications()

          • Hi!

            First question: Why is “$modLog4NET.value” empty? There you have to specify the XML data that have to be inserted into the web.config file…

            Second: In the “name” property you should insert a value that is adapted from the XML data (in the “Value” property).

            Please note: The XML data <add name='MyAuthenticationProvider' type'MyAuthenticationProvider.MyRoleProvider, " + $assembly + "' /> as in my sample script is only valid the the config entry inside the “providers” tag (XPath in web.config: “configuration/system.web/membership/providers”).

            In “configSection” you have diffrent data. Something like that:

            <configSections>
            <section name="ikTestSection" type="ikTestSection, ikTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b51f57d4fedabcde" />
            </configSections>

            your “Name” property should look like this:
            $modLog4Net.name = “section[@name='ikTestSection'][@type='ikTestSection," + $log4netAssembly + "']”

            and you need to specify the “Value” property!!! This should be:
            $modLog4Net.Value = "<section name='ikTestSection' type='ikTestSection," + $log4netAssembly + "' />"

            Hope this helps! – Please post your results!

            Kind regard
            Ingo

          • Hi Ingo,

            Many thanks for your help.

            This solution works for me. It seems how you code the changes into the web.config are really dependent on specific application settings with different mechanisms to implement them and there are no generics.

            For the time being this works and I would definitely seek more help in times of need.

            Many thanks once again.

            Regards,
            Anupam

          • Hi Ingo,

            Many thanks for your help.

            I am stuck again.

            Need to set up the log4net node under the configuration section. I tried something like under but this does not seem to work.

            $modLog4Net = New-Object -TypeName Microsoft.SharePoint.Administration.SPWebConfigModification

            $modLog4Net.path = “/configuration”

            $modLog4Net.type = 0

            $modLog4Net.name = “log4net [@xsi:noNamespaceSchemaLocation=’http://csharptest.net/downloads/schema/log4net.xsd’] [@xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’]”

            $modLog4Net.value = “”

            $modLog4Net.owner = “SEPortal”

            $modLog4Net.sequence = 0

            I get the following error :

            Exception calling “ApplyWebConfigModifications” with “0” argument(s): “Namespace Manager or XsltContext needed. This query has a pr
            efix, variable, or user-defined function.”

            Could you please help?

            Many thanks once again.

            Regards,
            Anupam

          • Hi!

            In my recent projects the way of making changes to the web.config was always the same. I would think it’s “generic”. Please feel free to post again !!

            kind regards
            ingo

          • Hi Ingo,

            I am now trying to modify the web.config of my target deployment server. I am trying to update the file entries which I want to take and change in the target destination which look like this:

            Although I have had some success with modifying most entries, I am not able to create the log4net entry with the xsi:noNamespaceSchemaLocation and xmlns:xsi attribute. During my research I came across the blog (http://blogs.devhorizon.com/reza/?p=459 )which says – SPWebConfigModification doesn’t have a property that would allow you to specify namespace (Point 5). So am not sure if what I am trying to achieve is possible using the SPWebconfigModification object.

            Following is the code that I’ve written (which obviously does not work).

            $executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

            [xml]$sourceWebConfig = get-content $executingScriptDirectoryArtifactsConfigurationweb.config

            $log4NetSettings = $sourceWebConfig.configuration

            $xxx = “http://csharptest.net/downloads/schema/log4net.xsd”

            $wa = Get-SPWebApplication $args[0]

            $modLog4Net = New-Object -TypeName Microsoft.SharePoint.Administration.SPWebConfigModification

            $modLog4Net.path = “/configuration”

            $modLog4Net.type = 0

            $modLog4Net.name = “log4net xsi:noNamespaceSchemaLocation= [xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’]”

            $modLog4Net.value = “”

            $modLog4Net.owner = “SEPortal”

            $modLog4Net.sequence = 0

            $wa.WebService.WebConfigModifications.Clear()

            $wa.WebService.WebConfigModifications.Add($modLog4Net)

            $wa.WebService.Update()

            $wa.WebService.ApplyWebConfigModifications()

            Will appreciate all your help here.

            Regards,
            Anupam

          • Hi Anupam,

            one more I’m missing a “Value” in line “$modLog4Net.value”…

            Please post the final web.config snipped. Let’s find a solution for your problem!!

            Kind regards
            Ingo

          • Hi Ingo,

            There’s no value to be set…the entry looks something like below in the web.config..

            Appreciate all your help.

  2. I am trying to add a new section below is the code:-

    # Load SharePoint PowerShell PSSnapIn and the main SharePoint .net library
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    $sharePointDLL = $ENV:CommonProgramFiles+(“Microsoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.dll”)
    [System.Reflection.Assembly]::LoadFile($sharePointDLL) | out-null

    # Show Farm BuildVersion to ensure the SharePoint .net library is loaded
    $localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
    $localFarm.BuildVersion

    # store some settings and objects in variables
    $webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($url)
    $farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq “Microsoft SharePoint Foundation Web Application” } )[0]

    # New web.config modifications for MyAuthenticationProvider
    $myModification1 = new-object “Microsoft.SharePoint.Administration.SPWebConfigModification”
    $myModification1.Path = “configuration/system.serviceModel/serviceHostingEnvironment”
    $myModification1.Name = “sectionGroup[@name=’baseAddressPrefixFilters’]”
    $myModification1.Sequence = 0
    $myModification1.Owner = “MyAuthenticationProvider”
    $myModification1.Type = 2 #for the enum value “SPWebConfigModification.SPWebConfigModificationType.EnsureSection”
    $myModification1.Value = “”
    $webapp.WebConfigModifications.Add($myModification1)

    # Update the Web Application and apply all exisiting web.config modifications including the new from above

    $webapp.Update()
    $farmServices.ApplyWebConfigModifications()

    But above code throws the following error:-

    You cannot call a method on a null-valued expression.
    At C:Usersv-srchalDesktopSpWebConfigMod.ps1:23 char:35
    + $webapp.WebConfigModifications.Add <<<< ($myModification1)
    + CategoryInfo : InvalidOperation: (Add:String) [], RuntimeExcept
    ion
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:Usersv-srchalDesktopSpWebConfigMod.ps1:28 char:15
    + $webapp.Update <<<< ()
    + CategoryInfo : InvalidOperation: (Update:String) [], RuntimeExc
    eption
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:Usersv-srchalDesktopSpWebConfigMod.ps1:29 char:42
    + $farmServices.ApplyWebConfigModifications <<<< ()
    + CategoryInfo : InvalidOperation: (ApplyWebConfigModifications:S
    tring) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    • Hi!

      I think you do not get a valid “SPWebApplication” object in line

      $webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($url)

      So this will crash:

      $webapp.WebConfigModifications.Add($myModification1)

      Please check it.

      regards
      Ingo

  3. Pingback: Editing the FIM Portal web.config in a farm topology | Yet another identity management blog

  4. As i had i Problem which i have solved now, i would like to share my Results.

    The Problem was, that i needed to add an attribute into an existing node in web.config, this is the way i did now:

    $myModification1.Name = “DynamicChildLimit”
    $myModification1.Path = “configuration/system.web/siteMap/providers/add[@name=’CurrentNavigation’]”
    $myModification1.Type = “EnsureAttribute”
    $myModification1.Value = “50”

    through try and error i figured out how to access a specific element which is added via you can see above the code, hope it might help you.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.