iomdesign
iomdesign

Reputation: 73

How to create location/ when it doesn't exist in applicationHost.config with Powershell and IISAdministration module

Any ideas how to add a new element to the root of the applicationHost.config using IISAdministration module?

I'd cobbled together the current code (edited for brevity) to bootstrap a new site in IIS 10.

Import-Module IISAdministration
$Manager = Get-IISServerManager
$Name = "my.sitedomain.foo"
$Config = $Manager.GetApplicationHostConfiguration()
$Config.GetSection("system.webServer/security/dynamicIpSecurity",$Name)
$DIPSecurity = $Config.GetSection("system.webServer/security/dynamicIpSecurity",$Name)
if($DIPSecurity -ne $null){
    $DIPSecurity.GetChildElement("denyByRequest") | %{
        $_.SetAttributeValue("enabled",$true)
        $_.SetAttributeValue("maxRequests",20)
        $_.SetAttributeValue("requestIntervalInMilliseconds",200)
    }            
}

When the dynamicIpSecurity element has been modified via IIS Manager then the xml gets added to the config file. Out-of-the-box, however, my IIS applicationHost.config does not have a <location> child element for the site.

The intention is to check if the location element exists and if not, add something like the following

<location path="my.sitedomain.foo">
    <system.webServer>
        <security>
            <dynamicIpSecurity>
                <denyByConcurrentRequests enabled="true" />
                <denyByRequestRate enabled="true" />
            </dynamicIpSecurity>
        </security>
    </system.webServer>
</location>

Many thanks, James

Upvotes: 0

Views: 581

Answers (1)

iomdesign
iomdesign

Reputation: 73

My question was phrased poorly. Really, I should have asked "How do I configure dynamicIpSecurity for a specific site using IISAdministration powershell module?".

Due to my limited knowledge of IISAdministration and Microsoft.Web.Administration, my attention was focused on the wrong hurdle. The solution to the correct question came re-reading https://learn.microsoft.com/en-us/iis/manage/scripting/how-to-use-microsoftwebadministration#set-configuration-in-site-root-webconfig (thanks to Lex Li for shifting my thinking).

By using ServiceManager.GetWebConfiguration("name.ofyour.site") instead of using ServiceManager.GetApplicationHostConfiguration() you get the configuration object for the specified website which includes all configuration elements regardless of the file where that configuration is actually written to.

Upvotes: 1

Related Questions