Iis – How to update HTTP custom headers in IIS6 using Powershell

iisiis-6powershellwmi

I have the following Powershell script which uses WMI to update the HTTP custom headers on a website in IIS 6.

The script seems to work fine, no errors generated, and the resultant $website object correctly shows the updated HttpCustomHeaders value. When I look at that site in IIS, though, the values have not been updated. This is also verified by visiting the site and looking at the headers in Firebug – the values are not saved.

Any ideas what I'm doing wrong?

$website = Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" -ComputerName $computerName -filter "ServerComment = '$websiteName'" -Authentication 6

$headers = $webSite.HttpCustomHeaders
$headers[0].Keyname = 'P3P: policyref="http://somewebsite.com/p3p.xml", CP="IDC DSP COR CUR DEV PSA IVA IVD CONo HIS TELo OUR DEL UNRo BUS UNI"'
$headers[0].Value = $null
$website.HttpCustomHeaders = $headers
$website.Put()

I'm more than open to an alternative script that provides a better way of setting this value as above assumes there is already at least one header present.

I've also tried Set-WmiInstance -InputObject $website instead of $website.Put() but that made no difference.

Best Answer

Your code example saves the value to the metabase but it saves to the root object (w3svc/1) instead of the root vdir (w3svc/1/root).

Here's what will work in place of what you have:

$website = Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" -ComputerName $computerName -filter "ServerComment = '$websiteName'" -Authentication 6

$path = $website.name + '/root'
$vdir = [wmi]"root\MicrosoftIISv2:IIsWebVirtualDirSetting='$path'"

$headers = $vdir.HttpCustomHeaders
$headers[0].Keyname = 'P3P: policyref="http://somewebsite.com/p3p.xml", CP="IDC DSP COR CUR DEV PSA IVA IVD CONo HIS TELo OUR DEL UNRo BUS UNI"'
$headers[0].Value = $null
$vdir.HttpCustomHeaders = $headers
$vdir.Put()

However, one more thing to watch for is that that replaces the first value rather than adding a new value. I'm out of time today to figure out how to do with with my limited PowerShell expertise, but it's going to be something along the lines of:

$bindingClass = [wmiclass]'root\MicrosoftIISv2:HttpCustomHeader'
$newheader = $bindingClass.CreateInstance()
$newheader.KeyName = "New Value"
$newheader.Value = $null

$headers += $header

There's a casting error so it's not quite right, but hopefully that points you in the right direction.