Tuesday, October 25, 2011

IIS PowerShell and Type Mismatch when Set-Item

If you cannot tell I have been doing a lot with PowerShell and web sites (IIS) lately. 

Let’s just say that it is amazing what you can do with an Azure Web Role when you get creative and are not afraid of scripts.  Oh, and since this is Azure, it is IIS 7.

A couple time now I have run into an error with IIS where I am unable to apply settings using Set-Item.

The error I get in return is rather cryptic and gives no leads as to the real culprit:

$dsAppPool | Set-Item
Set-Item : Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
At line:1 char:22
+ $dsAppPool | Set-Item <<<<
    + CategoryInfo          : InvalidArgument: (:) [Set-Item], COMException
    + FullyQualifiedErrorId : path,Microsoft.PowerShell.Commands.SetItemCommand

I don’t know about you, but this error does not give me much to go on, well a little; I know I have a type mismatch.

In this specific example I am setting an application pool to run under a user account.

I fetch my username and password into a variable.  These are strings.

But when I do a GetType() against the variable it returns as a String, system.object.  And this is the root of the type mismatch.

A simple cast to string fixes the problem:

$dsAppPool = (Get-ChildItem IIS:\AppPools | where {$_.Name -match ("Authentication")} )
$dsAppPool.processModel.identityType = "SpecificUser"
$dsAppPool.processModel.userName = [string]$siteUser
$dsAppPool.processModel.password = [string]$siteUserPwd
$dsAppPool | Set-Item

The same thing works in other areas of Application Pools as well.  Here I am modifying the default IIS cache flushing behavior (note the timespan declarations):

$mooAppPool = ( Get-ChildItem IIS:\AppPools | where {$_.Name -match ("Moo")} )

$mooAppPool.processModel.idleTimeout = [System.TimeSpan]::FromMinutes(43200)  # Idle Time-Out
$mooAppPool.recycling.periodicRestart.time = [System.TimeSpan]::FromMinutes(432000)  # Regular Time Interval

$mooAppPool | Set-Item

$schPath = $mooAppPool.ItemXPath + "/recycling/periodicRestart"
$p = $mooAppPool.recycling.periodicRestart.schedule.Collection.Count

Do {
    Remove-WebconfigurationProperty $schPath -Name schedule.collection -AtIndex ($p - 1) -Force
Until ($p -eq "0")


Anonymous said...

This helps me a lot. Thanks!

Anonymous said...

Had the same problem, thanks for the fix.

Anonymous said...

you are a lifesaver! i was encountering this, but only in certain pipeline situations, it was driving me NUTS!