如何使用 Powershell 更改 IIS 預設文檔順序?

如何使用 Powershell 更改 IIS 預設文檔順序?

我怎樣才能確定預設.aspx是我的 IIS 網站的第一個預設文件嗎?

我努力了:

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

但如果預設.aspx已經在它抱怨的清單中

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

如果需要,如何添加它,如果尚不存在,如何將其移動到列表頂部?

答案1

訣竅是刪除“default.aspx”(如果它已位於清單中的任何位置):

$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}

我們首先檢查 default.aspx 是否存在,如果找到,請將其刪除,然後將其加回頂部,就像您已經做的那樣。

答案2

對於那些可能覺得它有用的人:我想配置 IIS,使其default.aspx成為 Web 伺服器的第一個預設文件。如果這就是您想要做的,這是腳本:

#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
}

該腳本檢查是否default.aspx設定為預設文件。如果default.aspx是預設文檔,它會檢查它是否位於清單中的第一個文檔。如果default.aspx位於清單中但不是第一個,則腳本會將其刪除。如果default.aspx未設定為預設文檔或它不是清單中的第一個文檔,則腳本會將其新增為清單中的第一個文件。

上面的腳本是 IIS GUI 配置,相當於單擊伺服器節點,雙擊Default Document右側窗格,然後移動default.aspx到第一個位置(如果不在清單中,則將其新增至第一個位置)。

相關內容