简体   繁体   English

使用 Powershell 编辑 IIS 自定义响应标头

[英]Edit IIS Custom Response Header using Powershell

I am writing a remote PowerShell script to use in Azure DevOps, the script is to edit an IIS HTTP Response Header for a specific site.我正在编写一个远程 PowerShell 脚本以在 Azure DevOps 中使用,该脚本用于编辑特定站点的 IIS HTTP 响应标头。 The code below is to add it, but what I am missing is to edit an existing header.下面的代码是添加它,但我缺少的是编辑现有的标题。

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

Ok i added a remove before the add好的,我在添加之前添加了删除

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

I would suggest a simpler approach.我会建议一个更简单的方法。

To set the existing header $headerName to value: $headerValue将现有标头$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}

To add the new header $headerName with 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}

And for completeness, to get value of the existing header $headerName :为了完整$headerName ,要获取现有标头$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM