如何用PowerShell筛选非指定Name和Value的IIS HTTP响应头
First, let's fix how we retrieve the headers so we have structured data to work with. Your current code extracts raw attributes as a flat list, which makes filtering tricky. Instead, we can convert each header into a PowerShell object with clear Name and Value properties:
$iisWebsiteName = "Default Web Site" $IISManager = New-Object Microsoft.Web.Administration.ServerManager $IISConfig = $IISManager.GetWebConfiguration($iisWebsiteName) $httpProtocolSection = $IISConfig.GetSection("system.webServer/httpProtocol") $customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders") # Convert each header to a structured object for easy filtering $allHeaders = $customHeadersCollection | ForEach-Object { [PSCustomObject]@{ Name = $_.Attributes["name"].Value Value = $_.Attributes["value"].Value } }
Now $allHeaders will show a clean, tabular list like this (example):
Name Value ---- ----- X-Powered-By ASP.NET Referrer-Policy no-referrer X-Content-Type-Options nosniff
Filtering for Your Target Headers
You mentioned wanting headers that do not match the exact combination of Name = "X-Powered-By" AND Value = "ASP.NET". This means we keep all headers except that specific pair. Use this filter:
$filteredHeaders = $allHeaders | Where-Object { -not ($_.Name -eq "X-Powered-By" -and $_.Value -eq "ASP.NET") }
If you actually meant a stricter filter—headers where Name is NOT "X-Powered-By" AND Value is NOT "ASP.NET" (excluding any header named X-Powered-By, regardless of value, and any header with value ASP.NET, regardless of name)—use this instead:
$filteredHeaders = $allHeaders | Where-Object { $_.Name -ne "X-Powered-By" -and $_.Value -ne "ASP.NET" }
View the Results
Simply output the filtered list to see your target headers:
$filteredHeaders
Why This Works
- Converting each configuration element to a
PSCustomObjectlets us use PowerShell's built-inWhere-Objectcmdlet for intuitive filtering. - We directly access the
nameandvalueattributes from the IIS configuration elements, avoiding the unstructured raw attribute output you were getting before.
内容的提问来源于stack exchange,提问作者bizna

