我使用 VS2010、PowerShell v2.0、Windows Server 2008 R2 Standard 为 Web 应用程序(IIS 7)创建部署脚本 ps1。
我想使用 Powershell 以编程方式管理 IIS 7(网站、appPools、virtualDirs 等)。
我对使用 Powershell 管理 IIS 的几种方法感到困惑。
推荐的方法是什么?
1)。使用 Microsoft.Web.Administration.dll
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")
2)。根据操作系统版本或 IIS 版本使用 Import-Module 与 Add-PSSnapin (¿?)
检测操作系统版本:
if ([System.Version] (Get-ItemProperty -path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion").CurrentVersion -ge [System.Version] "6.1") { Import-Module WebAdministration } else { Add-PSSnapin WebAdministration }
检测 IIS 版本
$iisVersion = Get-ItemProperty "HKLM:\software\microsoft\InetStp";
if ($iisVersion.MajorVersion -eq 7)
{
if ($iisVersion.MinorVersion -ge 5)
{
Import-Module WebAdministration;
}
else
{
if (-not (Get-PSSnapIn | Where {$_.Name -eq "WebAdministration";})) {
Add-PSSnapIn WebAdministration;
}
}
}
模块加载并加载为 Snapin:
$ModuleName = "WebAdministration"
$ModuleLoaded = $false
$LoadAsSnapin = $false
if ($PSVersionTable.PSVersion.Major -ge 2)
{
if ((Get-Module -ListAvailable | ForEach-Object {$_.Name}) -contains $ModuleName)
{
Import-Module $ModuleName
if ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName)
{
$ModuleLoaded = $true
}
else
{
$LoadAsSnapin = $true
}
}
elseif ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName)
{
$ModuleLoaded = $true
}
else
{
$LoadAsSnapin = $true
}
}
else
{
$LoadAsSnapin = $true
}
if ($LoadAsSnapin)
{
if ((Get-PSSnapin -Registered | ForEach-Object {$_.Name}) -contains $ModuleName)
{
Add-PSSnapin $ModuleName
if ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName)
{
$ModuleLoaded = $true
}
}
elseif ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName)
{
$ModuleLoaded = $true
}
}