Created
November 7, 2016 09:16
-
-
Save donaldgray/7a4ff985705eac49f29dd3639987c155 to your computer and use it in GitHub Desktop.
Powershell script for setting IIS header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$PSPath = 'MACHINE/WEBROOT/APPHOST/' + $WebsiteName | |
$Filter = 'system.webServer/httpProtocol/customHeaders' | |
# Ensure working with IIS 7 and 7.5(+?) | |
try { | |
Add-PSSnapin WebAdministration | |
} | |
catch { | |
try { | |
Import-Module WebAdministration | |
} | |
catch { | |
Write-Warning "We failed to load the WebAdministration module. This usually resolved by doing one of the following:" | |
Write-Warning "1. Install .NET Framework 3.5.1" | |
Write-Warning "2. Upgrade to PowerShell 3.0 (or greater)" | |
throw ($error | Select-Object -First 1) | |
} | |
} | |
# First check if the header exists | |
$customHeadersCollection = Get-WebConfiguration -Filter $Filter -PSPath $PSPath | |
$exists = $false | |
foreach($path in $customHeadersCollection.GetCollection()){ | |
if ($path.GetAttributeValue("name") -eq $HeaderName){ | |
Write-Host "Header $HeaderName already exists" | |
$exists = $true | |
break | |
} | |
} | |
# Delete the header if it exists.. | |
if ($exists){ | |
Write-Host "Removing header $HeaderName" | |
Remove-WebConfigurationProperty -PSPath $PSPath -Name . -Filter $Filter -AtElement @{name =$HeaderName } | |
} | |
# Add the new header | |
Write-Host "Adding header $HeaderName with value $HeaderValue" | |
Add-WebConfigurationProperty -pspath $PSPath -filter $Filter -name . -AtElement @{name=$HeaderName; value=$HeaderValue} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Donaldgray, thank you very much for the code idea, it helped!