Building Active Directory Records Using PowerShell Works in IIS 6, but Not in IIS 7

The following PowerShell line works with IIS 6 installed:

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

However, with IIS 7, it throws the following error if the IIS 6 compatibility role service is not 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 using IIS-7?

thanks

+3
source share
2 answers

There are several ways to do this using APPCMDboth C # / VB.NET / JavaScript / VBScript:

Custom Headers (IIS.NET)

To do this, using PowerShell and assembly 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()

This will lead to the path <location>in applicationHost.configwith the following:

<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 Server 2008 SP2.

+3

Source: https://habr.com/ru/post/1722518/


All Articles