There are a number of ways to do this using APPCMD
and C#/VB.NET/JavaScript/VBScript:
Custom Headers (IIS.NET)
To do this using PowerShell and the Microsoft.Web.Administration
assembly:
[Reflection.Assembly]::Load("Microsoft.Web.Administration, Version=7.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")
$serverManager = new-object Microsoft.Web.Administration.ServerManager
$siteConfig = $serverManager.GetApplicationHostConfiguration()
$httpProtocolSection = $siteConfig.GetSection("system.webServer/httpProtocol", "Default Web Site")
$customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders")
$addElement = $customHeadersCollection.CreateElement("add")
$addElement["name"] = "X-Custom-Name"
$addElement["value"] = "MyCustomValue"
$customHeadersCollection.Add($addElement)
$serverManager.CommitChanges()
This will result in a <location>
path in applicationHost.config
with the following:
<location path="Default Web Site">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Custom-Name" value="MyCustomValue" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
To do this in PowerShell using the new IIS 7 PowerShell Snap-In:
add-webconfiguration `
-filter /system.webServer/httpProtocol/customHeaders `
-location "Default Web Site" `
-pspath "IIS:" `
-value @{name='X-MyHeader';value='MyCustomHeaderValue'} `
-atindex 0
This will configure a <location>
path in applicationHost.config
with the following:
<location path="Default Web Site">
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-MyHeader" value="MyCustomHeaderValue" />
<add name="X-Powered-By" value="ASP.NET" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
The back-ticks at the end of each line indicate a line continuation. The two examples given above were tested on Windows 2008 Server SP2.