1

Does anyone know how to use Powershell to create a 'Deny File Name Extension' rule, so that certain files will not be served by IIS?

For example, I want to set a rule to deny all .txt files from being served up with IIS.

thank you

4

How about this:

[Reflection.Assembly]::Load(
"Microsoft.Web.Administration, Version=7.0.0.0, 
Culture=Neutral, PublicKeyToken=31bf3856ad364e35") > $null

$serverManager = New-Object Microsoft.Web.Administration.ServerManager

# Default Web Site
$siteId = 1
$site = $serverManager.Sites | where { $_.Id -eq $siteID }   

#
# Sets the filter in the site's web.config
#
$config = $site.GetWebConfiguration()
$requestFilteringSection = `
      $config.GetSection("system.webServer/security/requestFiltering")

#
# Or delete last two lines and use next two instead to set in applicationHost.config
#
# $config = serverManager.GetApplicationHostConfiguration();
# $requestFilteringSection = `
    $config.GetSection("system.webServer/security/requestFiltering", $site.Name);

$fileExtensionsElement = `
      $requestFilteringSection.GetChildElement("fileExtensions")
$fileExtensionsCollection = $fileExtensionsElement.GetCollection()
$addElement = $fileExtensionsCollection.CreateElement("add")
$addElement["fileExtension"] = ".txt"
$addElement["allowed"] = $false
$fileExtensionsCollection.Add($addElement)

$serverManager.CommitChanges()

You could also use appcmd.exe:

Configure in site web.config:

appcmd.exe set config "Default Web Site" -section:system.webServer/security/requestFiltering /+"fileExtensions.[fileExtension='.txt',allowed='False']" 

Or configure in applicationHost.config:

appcmd.exe set config "Default Web Site" -section:system.webServer/security/requestFiltering /+"fileExtensions.[fileExtension='.bong',allowed='False']" /commit:apphost

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.