4

以下 PowerShell 行适用于安装的 IIS 6:

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

但是,对于 IIS 7,除非安装了 IIS 6 管理兼容性角色服务,否则它会引发以下错误:

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

我的目标是修改 HttpCustomHeaders:

$service.HttpCustomHeaders = $foo

如何以符合 IIS-7 的方式执行此操作?

谢谢

4

2 回答 2

3

APPCMD使用C#/VB.NET/JavaScript/VBScript有多种方法可以做到这一点:

自定义标头 (IIS.NET)

要使用 PowerShell 和Microsoft.Web.Administration程序集执行此操作:

[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()

这将导致以下<location>路径applicationHost.config

<location path="Default Web Site">
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="X-Custom-Name" value="MyCustomValue" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</location>

要在 PowerShell 中使用新的 IIS 7 PowerShell 管理单元执行此操作:

add-webconfiguration `
   -filter /system.webServer/httpProtocol/customHeaders `
   -location "Default Web Site" `
   -pspath "IIS:" `
   -value @{name='X-MyHeader';value='MyCustomHeaderValue'} `
   -atindex 0

这将使用以下内容配置<location>路径applicationHost.config

<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>

每行末尾的反引号表示续行。上面给出的两个示例在 Windows 2008 Server SP2 上进行了测试。

于 2009-11-11T17:59:20.977 回答
1

现在有一个 IIS 7 PowerShell 管理单元:

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

于 2009-11-10T22:35:40.710 回答