1

我使用 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
    }
}

参考资料:
http ://forums.iis.net/t/1166784.aspx/1

PowerShell:在 IIS 7 和 IIS 7.5 上的 ps1 脚本中加载 WebAdministration

4

1 回答 1

1

由于您说您使用的是 Server 2008 R2 和 Powershell V2 或更高版本,因此 Import-Module 是首选方法。模块比管理单元更强大,并添加了更多功能。然而最大的不同是模块不需要注册(添加到注册表中)。

管理单元是 Powershell V1 中不支持模块的遗留功能。Server 2008(原始配方)没有开箱即用的 V2,仍然使用 IIS、ActiveDirectory、Exchange 等管理单元

Server 2008 R2 包括 Powershell V2,因此可以使用模块。

它归结为以下几点:

if (YourSystems are all Server 2008 R2) {
    Import the module and ignore the rest.
} elseif (One or more of the servers being managed is still on 2008 (original)) {
    Use the snapin.
}
于 2013-07-15T02:03:46.870 回答