首页 > 解决方案 > Powershell 添加重复的 IIS 应用程序池

问题描述

我有以下 Powershell 脚本来在 IIS 中创建应用程序池和网站。该脚本在我第一次运行它时添加了应用程序池(当应用程序池不存在时)但是当我第二次运行脚本时,虽然应用程序池存在,但脚本找不到它并尝试再次创建它. 导致异常!

$WebsiteName="search-api"
$AppPoolName="search-api"
$Runtime=""   # Empty = Not Managed
$Port = 3050
$PhysicalPath="C:\Applications\SearchApi"

import-module WebAdministration

clear

New-Item -Path $PhysicalPath -Force

$AppPool = Get-IISAppPool -Name $AppPoolName

If ($AppPool.Length -eq 0)
{ 
    $AppPool = New-WebAppPool -Name $AppPoolName -Force 
    $appPool | Set-ItemProperty -Name "managedRuntimeVersion" -Value $Runtime
}


$TheWebSite = Get-Website -Name $WebsiteName

If ($TheWebSite -eq $null)
{
    New-Website -Name $WebsiteName -Port $Port -IPAddress "*" -ApplicationPool $AppPoolName -PhysicalPath  $PhysicalPath -Force 
}

标签: powershelliis

解决方案


第一:避免PropertyNotFoundException

If ( $AppPool.Length -eq 0 ) {  }

在此对象上找不到属性“长度”。验证该属性是否存在。

改为使用If ( $null -eq $AppPool ) { }

第二:在使用 Get-IISAppPool 并在同一会话中创建新的应用程序池时,阅读AdminOfThings对 Odd 问题的回答。

要么申请Reset-IISServerManager(可能需要确认),

或者,代替Get-IISAppPool -Name $AppPoolName,使用

Get-ChildItem IIS:\AppPools | Where-Object Name -eq $AppPoolName

第三New-WebSite文档说关于-PhysicalPath参数:

指定新站点的物理路径。指定的文件夹 必须已经存在。

利用New-Item -Path $PhysicalPath -Force -ItemType Directory


推荐阅读