I need to iterate all authentication modes for an IIS Application and disable all except one.
something like:
foreach($itm in [collection of authentication modes for app]){
if([certain authentication]){enabled = true}else{enabled = false}}
I'm familiar with Set-WebConfigurationProperty.
You can iterate all native (as well as any installed third-party) authentication modes for the root web application for a given site by calling Get-WebConfiguration:
$siteName = "MySiteName"
$authentications = Get-WebConfiguration `
-filter "system.webServer/security/authentication/*" `
-PSPath "IIS:\Sites\$siteName"
You can also iterate the authentication modes for any given web application in the site (or even specific file(s)). The following retrieves the authentication modes for a contrived web application called "\foo":
$authentications = Get-WebConfiguration `
-filter "system.webServer/security/authentication/*" `
-PSPath "IIS:\Sites\$siteName\foo"
The SectionPath property can be used to examine the authentication mode, e.g.:
$authentications | foreach {$_.SectionPath}
Which outputs:
/system.webServer/security/authentication/digestAuthentication
/system.webServer/security/authentication/anonymousAuthentication
/system.webServer/security/authentication/iisClientCertificateMappingAuthentication
/system.webServer/security/authentication/basicAuthentication
/system.webServer/security/authentication/clientCertificateMappingAuthentication
/system.webServer/security/authentication/windowsAuthentication
You might think you could do something as simple as this in your foreach loop...
$authentications | `
foreach { $_.Enabled = $_.SectionPath.EndsWith('\windowsAuthentication') }
...but there's a problem. It doesn't work. It won't actually fail with an error, but it won't change anything either.
That's because authentication sections are locked. To change a setting in a locked section, you need to call Set-WebConfigurationProperty and include the -Location parameter, e.g.,
Set-WebConfigurationProperty `
-filter "/system.webServer/security/authentication/windowsAuthentication" `
-name enabled -value true -PSPath "IIS:\" -location $siteName
I suppose you can still pipe the objects to the foreach-object cmdlet but it's probably going to be a lot easier to read (and maintain) if you script this using a foreach loop.
$siteName = "MySiteName"
$authentications = Get-WebConfiguration `
-filter "system.webServer/security/authentication/*" `
-PSPath "IIS:\Sites\$siteName"
foreach ($auth in $authentications)
{
$auth.SectionPath -match "/windowsAuthentication$"
$enable = ($matches.count -gt 0)
Set-WebConfigurationProperty `
-filter $auth.SectionPath `
-name enabled -value $enable -PSPath "IIS:\" -location $siteName
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With