【问题标题】:Edit IIS Custom Response Header using Powershell使用 Powershell 编辑 IIS 自定义响应标头
【发布时间】:2020-01-17 05:41:57
【问题描述】:

我正在编写要在 Azure DevOps 中使用的远程 PowerShell 脚本,该脚本用于编辑特定站点的 IIS HTTP 响应标头。下面的代码是添加它,但我缺少的是编辑现有的标题。

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration") | Out-Null
$iis = new-object Microsoft.Web.Administration.ServerManager
$config = $iis.GetWebConfiguration("Test")
$httpProtocolSection = $config.GetSection("system.webServer/httpProtocol")
$customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders")
$addElement = $customHeadersCollection.CreateElement("add")
$addElement["name"] = "X-Custom-Name"
$addElement["value"] = "xxx"
$customHeadersCollection.Add($addElement)
$iis.CommitChanges()

【问题讨论】:

    标签: powershell iis azure-devops


    【解决方案1】:

    好的,我在添加之前添加了一个删除

    $PSPath =  'MACHINE/WEBROOT/APPHOST/$(IISName)' 
    Remove-WebConfigurationProperty -PSPath $PSPath -Name . -Filter system.webServer/httpProtocol/customHeaders -AtElement @{name ="X-Robots-Tag"}
    

    【讨论】:

    • 嗨,非常感谢这里分享的这个解决方案。您可以接受此答案,因此其他 SO 用户将能够查看该解决方案是否有效:-)
    【解决方案2】:

    我会建议一种更简单的方法。

    将现有标头$headerName 设置为值:$headerValue

    import-module WebAdministration
    Set-WebConfigurationProperty `
        -Filter "system.webServer/httpProtocol/customHeaders" `
        -PSPath IIS:\Sites\$siteName -Name . `
        -AtElement @{name=$headerName} `
        -Value @{name=$headerName;value=$headerValue}
    

    添加新标头$headerName,其值为:$headerValue

    import-module WebAdministration
    Add-WebConfigurationProperty `
        -Filter "system.webServer/httpProtocol/customHeaders" `
        -PSPath IIS:\Sites\$siteName -Name . `
        -AtElement @{name=$headerName} `
        -Value @{name=$headerName;value=$headerValue}
    

    为了完整起见,获取现有标头 $headerName 的值:

    import-module WebAdministration
    $customHeaders = Get-WebConfigurationProperty `
        -Filter "system.webServer/httpProtocol/customHeaders" `
        -PSPath IIS:\Sites\$siteName -Name . `
    $customHeader = $customHeaders.Collection | where-object { $_.name -eq $headerName })
    $headerValue = $customHeader.value
    
    

    【讨论】:

      猜你喜欢
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2017-08-16
      • 2013-07-08
      相关资源
      最近更新 更多