繁体   English   中英

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

[英]Edit IIS Custom Response Header using Powershell

我正在编写一个远程 PowerShell 脚本以在 Azure DevOps 中使用,该脚本用于编辑特定站点的 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()

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

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

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

将现有标头$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 ,要获取现有标头$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