PowerShell : Add custom HTTP Response Header to IIS

Create custom HTTP Response Header to IIS site using this PowerShell script.

1,409 times
Add to favorites
E-mail Twitter del.icio.us Digg Facebook
Sign in to ask a question

  • Is it possible to do this remotely?
    1 Posts | Last post February 05, 2019
    • I am wondering how to do this remotely with Wmi-Object...
      Is this possible?
  • Error Encountered:
    1 Posts | Last post October 15, 2018
    • Hello!
      I tried to use the script but I encountered this error.
      Exception setting "CursorPosition": "The Win32 internal error "The handle is 
      ".\SetHTTPResponseHeader.ps1" "Default Web Site" "Strict-Transport-Security" "max-age= 31536000; includeSubdomains"
      invalid" 0x6 occurred while trying to set the cursor position. Contact 
      Microsoft Customer Support Services."
      At line:3 char:1
      + $RawUI.CursorPosition = @{X=0;Y=0}
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationExceptio 
          + FullyQualifiedErrorId : ExceptionWhenSetting
      Exception calling "SetBufferContents" with "2" argument(s): "The Win32 
      internal error "The handle is invalid" 0x6 occurred while filling the console 
      output buffer with characters. Contact Microsoft Customer Support Services."
      At line:4 char:1
      + $RawUI.SetBufferContents(
      + ~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
          + FullyQualifiedErrorId : HostException
      write-host : The Win32 internal error "The handle is invalid" 0x6 occurred 
      while setting character attributes for the console output buffer. Contact 
      Microsoft Customer Support Services.
      At D:\home\httpHeader\SetHTTPResponseHeader.ps1:49 char:5
      +     write-host "Error" $_.Exception.Message
      +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : ResourceUnavailable: (:) [Write-Host], HostExcep 
          + FullyQualifiedErrorId : SetConsoleTextAttribute,Microsoft.PowerShell.Com 
  • Instead of WebSite name - port number
    1 Posts | Last post September 28, 2018
    • hi Avijit,
      instead of using Website name 
      $config = $iis.GetWebConfiguration("Default Web Site")
      do we have the option to supply WEBSITE URI?
  • Apply to all site
    2 Posts | Last post February 03, 2017
    • How can I add the http response header to all of the sites in IIS? Or is there a way to have it read from a file with the names of the IIS Sites that I was to apply this to?
    • Please find the updated script to add the http response header to all of the sites in IIS:
         #[string]$WebSiteName = $(throw "The web site name must be provided."),
         [string]$HeaderName = $(throw "The header name must be provided."),
         [string]$HeaderValue = $(throw "The header vale must be provided.")
      # Initialize the default script exit code.
      $exitCode = 0
      	$iisVersion = Get-ItemProperty "HKLM:\software\microsoft\InetStp";
      	if ($iisVersion.MajorVersion -eq 7)
      		if ($iisVersion.MinorVersion -ge 5)
      			Import-Module WebAdministration;
      			if (-not (Get-PSSnapIn | Where {$_.Name -eq "WebAdministration";})) {
      				Add-PSSnapIn WebAdministration;
          $iis = new-object Microsoft.Web.Administration.ServerManager
      	foreach ($webapp in Get-ChildItem -Path IIS:\Sites)
              $WebSiteName = $webapp.name
      	    $PSPath =  'MACHINE/WEBROOT/APPHOST/' + $WebSiteName
              Remove-WebConfigurationProperty -PSPath $PSPath -Name . -Filter system.webServer/httpProtocol/customHeaders -AtElement @{name =$HeaderName }
              $config = $iis.GetWebConfiguration($WebSiteName) #i.e. "Default Web Site"
              $httpProtocolSection = $config.GetSection("system.webServer/httpProtocol")
              $customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders")
              $addElement = $customHeadersCollection.CreateElement("add")
              $addElement["name"] = $HeaderName
              $addElement["value"] = $HeaderValue
          write-host $iis
      Catch [System.Exception]
          $exitCode = 1
          write-host "Error" $_.Exception.Message
      # Indicate the resulting exit code to the calling process.
      if ($exitCode -gt 0)
          "`nERROR: Operation failed with error code $exitCode."
      exit $exitCode
  • Do you know how to resolve this error?
    3 Posts | Last post September 17, 2015
    • I'm getting the following error message on Server Core 2012R2:
      WARNING: Property . is not found on /system.webServer/httpProtocol/customHeaders at index @{name="X-Frame-Options"}.
      Error Cannot find type [Microsoft.Web.Administration.ServerManager]: verify that the assembly containing this type is loaded.
      ERROR: Operation failed with error code 1.
      The command I'm using is as follows:
      .\SetHTTPResponseHeader.ps1 "Default Web Site" "X-Frame-Options" "SAMEORIGIN"
      Does this script only work on Server with a GUI?
    • The problem is PowerShell has no idea where Microsoft.Web.Administration.DLL is so you have to tell it how to load it.
      I am not sure the IIS version you are using but type the following command:
      PS C:\> [System.Reflection.Assembly]::LoadFrom( "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" )
      For more details check the following links:
      Hope this will help you.
    • That actually worked.  I still get the warning message that I typed earlier, but the Raw Attributes seem to have taken hold.  I'm using IIS 7.  I would have never guessed that PowerShell is unaware of where to find the necessary .dll file.
      This is a very useful script as I needed it to configure IIS to prevent clickjacking on Server 2012 running in Core mode.  I was hoping to not have to install a GUI just to add an HTTP response header, only to remove the GUI minutes later.
      Thank you again for the PowerShell code as well as your quick reply to my issue!
  • How to do it on server leverl instead?
    2 Posts | Last post July 07, 2015
    • Subj
    • You have to change the line $config =$iis.GetApplicationHostConfiguration()
      [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration") | Out-Null
      $iis = new-object Microsoft.Web.Administration.ServerManager
      $config =$iis.GetApplicationHostConfiguration()
      $httpProtocolSection = $config.GetSection("system.webServer/httpProtocol")
      $customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders")
      $addElement = $customHeadersCollection.CreateElement("add")
      $addElement["name"] = "X-Custom-Name"
      $addElement["value"] = "MyCustomValue"