How can I change the IIS default document order using Powershell?

How can I make sure default.aspx is the first default document for my IIS website?

I have tried:

Add-WebConfiguration //defaultDocument/files "IIS:\sites\Default Web Site\MyWebSite" -atIndex 0 -Value @{value="Default.aspx"}

but if default.aspx is already in the list it complains

Add-WebConfiguration : Filename: 
Error: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'Default.aspx'

How can I add it if necessary and move it to the top of the list if it's not already there?


The trick is to remove 'default.aspx' if it is already anywhere in the list:

$filter = "system.webserver/defaultdocument/files"
$site = "IIS:\sites\Default Web Site\MyWebSite"
$file = "default.aspx"

if ((Get-WebConfiguration $filter/* "$site" | where {$_.value -eq $file}).length -eq 1)
{
   Remove-WebconfigurationProperty $filter "$site" -name collection -AtElement @{value=$file}
}

Add-WebConfiguration $filter "$site" -atIndex 0 -Value @{value=$file}

We first check for the existence of default.aspx, if found, remove it and then add it back in at the top, just like you already did.


For those that may find it useful: I wanted to configure IIS such that the default.aspx is the first default document for the web server. Here is the script if that's what you want to do:

#requires -RunAsAdministrator

$file = "default.aspx"
$baseFilter = "/system.webServer/defaultDocument/files"

$filter = "{0}/add[@value='{1}']" -f $baseFilter,$file
$fileExists = $null -ne (Get-WebConfigurationProperty $filter -Name ".")
$updateConfig = -not $fileExists
if ( $fileExists ) {
  $firstValue = Get-WebConfiguration "$baseFilter/*" |
    Select-Object -ExpandProperty value -First 1
  $updateConfig = $firstValue -ne $file
  if ( $updateConfig ) {
    Clear-WebConfiguration $filter -Verbose
  }
}
if ( $updateConfig ) {
  Add-WebConfiguration $baseFilter -AtIndex 0 -Value @{value = $file} -Verbose
}

The script checks if default.aspx is set as a default document. If default.aspx is a default document, it checks if it's first in the list. If default.aspx is in the list but not first, the script removes it. If default.aspx is not set as a default document or it's not first in the list, the script adds it as the first in the list.

The above script is the IIS GUI configuration equivalent of clicking the server node, double-clicking Default Document in the right pane, and moving default.aspx to the first position (or adding it in the first position if it's not in the list).