I use VS2010, PowerShell v2.0, Windows Server 2008 R2 Standard for create deploy scripts ps1 for web applications (IIS 7).
I want manage IIS 7 (websites, appPools, virtualDirs, etc) programmatically using Powershell.
I'm confused about several ways for manage IIS using Powershell.
Which is recommended way about it?
1). Using Microsoft.Web.Administration.dll
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")
2). Using Import-Module vs Add-PSSnapin, according OS version or IIS version (¿?)
Detect OS version:
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 }
Detect IIS version
$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;
}
}
}
Module loaded and load as 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
}
}
References:
http://forums.iis.net/t/1166784.aspx/1
PowerShell: Load WebAdministration in ps1 script on both IIS 7 and IIS 7.5