Posted in PowerShell

PowerShell – Adding custom HTTP Response Headers

Recently I needed to add a few custom HTTP Response Headers to a Website on an on-premise IIS, and as I will need to do this for multiple servers, I wanted to run a PowerShell script instead of doing it manually on each server.

I really thought that I would be able to quickly find a script to perform this task, but turns out it wasn’t that straight forward. It took me quite a while to get this working (I am no PowerShell expert).

Here is what my script is doing:

  • Create an array of custom object that will contain the Name and Value for the custom headers
  • Get the IIS Configuration for the Website
  • For each item of my array
    • Check if the header name already doesn’t exist in the configuration, and then create it
    • Commit the IIS changes (this is necessary otherwise an error is thrown that the object is in read-only mode)

You don’t really need to create an array and loop through the values, if you want to simplify your code, you can just copy & paste the New-IISConfigCollectionElement instruction multiple times, and this should work as well.

Below is the final script, all you need to do is change Website name and Custom Headers (name and value):

$Website = "My Website"

Import-Module IISAdministration

$CustomHeaders = @(
    [pscustomobject]@{Name="X-XSS-Protection"; Value="1; mode=block"}
    [pscustomobject]@{Name="X-Content-Type-Options"; Value="nosniff"}
    [pscustomobject]@{Name="Content-Security-Policy"; Value="default-src 'self'"}
    [pscustomobject]@{Name="Referrer-Policy"; Value="strict-origin"}
    [pscustomobject]@{Name="Feature-Policy"; Value="fullscreen 'self'"}
)

$CustomHeaders | ForEach-Object {
    $IISConfigSection = Get-IISConfigSection -SectionPath system.webServer/httpProtocol -CommitPath $Website | Get-IISConfigCollection -CollectionName "customHeaders";
    $Header = Get-IISConfigCollectionElement -ConfigCollection $IISConfigSection -ConfigAttribute @{ 'name' = $.Name }
    if(!$Header){
        New-IISConfigCollectionElement -ConfigCollection $IISConfigSection -ConfigAttribute @{"name"=$.Name; "value"=$_.Value;};
        $IIS = Get-IISServerManager
        $IIS.CommitChanges();
    }
}