views:

479

answers:

2

The following line of PowerShell works with IIS 6 installed:

$service = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC")

However, with IIS 7 it throws the following error unless the IIS 6 Management Compatibility role service is installed:

out-lineoutput : Exception retrieving member "ClassId2e4f51ef21dd47e99d3c952918aff9cd": "Unknown error (0x80005000)"

My goal is to modify the HttpCustomHeaders:

$service.HttpCustomHeaders = $foo

How can I do this in an IIS-7-compliant way?

Thanks

+1  A: 

There is now an IIS 7 PowerShell snap-in:

http://learn.iis.net/page.aspx/428/getting-started-with-the-iis-70-powershell-snap-in/

pm100
+1  A: 

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.

Kev