Windows PowerShell has become a must-have tool for IT administrators. One of the latest and greatest PowerShell features is its ability to interact with and manage Microsoft IIS 7. The IIS PowerShell Snap-In lets you create, configure, and manage IIS 7 websites, web applications, application pools, virtual directories, and .NET application domains using PowerShell commands or scripts. The snap-in works with PowerShell 2.0 and earlier.

The IIS PowerShell Snap-In interacts with the IIS Management Console, so this console is a prerequisite to running the snap-in. I'll show you how to install the IIS Management Console and get the PowerShell Snap-In running on Windows 7, Windows Vista, Windows Server 2008 R2, and Windows Server 2008. Then, I'll show you how to use the snap-in to perform common IIS tasks.

Installing the IIS Management Console

To install the IIS Management Console, you need Administrator privileges for the computer on which you're installing it. To install the console on Windows 7 or Vista, follow these steps:

  1. Select Control Panel on the Start menu.
  2. In Control Panel, click Programs.
  3. Click Turn Windows features on or off.
  4. Expand Internet Information Services.
  5. Expand Web Management Tools.
  6. Select IIS Management Console.
  7. Click the OK button to initiate the installation.

To install the console on Server 2008 R2 or Server 2008, follow these steps:

  1. On the Start menu, select All Programs, choose Administrative Tools, and click Server Manager.
  2. In Server Manager, select Roles in the left pane to bring up the Role Summary View.
  3. Click the Add Roles link to open the Add Roles Wizard.
  4. On the Before You Begin page, click Next.
  5. On the Select Server Roles page, click the Web Server (IIS) check box.
  6. A dialog box will appear asking if you want to add the role services and features required for Web Server (IIS) support. Click Add Required Role Services to close the dialog box and return to the Select Server Roles page. Click Next.
  7. An information dialog box will appear at this point. Click Next to proceed to the Select Role Services page.
  8. On the Select Role Services page, expand Internet Information Services.
  9. Under Web Management Tools, select IIS Management Console. Click Next.
  10. If you're running Server 2008, click Install on the Confirm Installation Options page. You'll see an Installation Progress dialog box. After the installation has completed, click the Close button to return to Server Manager. If you're running Server 2008 R2, click Close right away, since the installation step is unnecessary.

When you install the IIS Management Console as just described, there's a noteworthy difference between Server 2008 and Server 2008 R2 and between Windows 7 and Vista. Server 2008 R2 and Windows 7 come with IIS 7.5, whereas Server 2008 and Windows Vista come with IIS 7.0. This distinction is important because IIS 7.5 includes the IIS PowerShell Snap-In, but IIS 7.0 doesn't include it. Therefore, to show you how to get the snap-in up and running, I've broken the discussion into two sections. Which one you should look at depends on your OS:

  • If you're using Server 2008 or Vista, read the "Getting the Snap-In Running on Server 2008 and Vista" section. You can skip the "Getting the Snap-In Running on Server 2008 R2 and Windows 7" section if you'd like.
  • If you're running Server 2008 R2 or Windows 7, read the "Getting the Snap-In Running on Server 2008 R2 and Windows 7" section. You can skip the "Getting the Snap-In Running on Server 2008 and Vista" section if you'd like.

Getting the Snap-In Running on Server 2008 and Vista

If you're running Server 2008 or Vista, you need to install and register the IIS PowerShell Snap-In because IIS 7.0 doesn't include it. You can download the snap-in from the Windows PowerShell Snap-In web page. Installing the snap-in is as easy as running a Windows Installer (.msi) file. The wizard takes care of the rest, including creating a shortcut for it on the Start menu.

Before you can use the IIS PowerShell Snap-In, you need to register it with PowerShell. You can automatically register the snap-in by selecting All Programs on the Start menu, choosing IIS 7.0 Extensions, and clicking the IIS PowerShell Management Console shortcut. You need Administrator privileges to manage IIS 7 configurations, so if you're logged on to Windows with an account that doesn't have Administrator privileges, you'll need to start the IIS PowerShell Management Console using the Run as administrator option, as Figure 1 shows.

Starting the IIS PowerShell Management Console

The prompt of the new PowerShell command window will be set to IIS:\, which is the root of the snap-in namespace.

If you want to manually register the IIS PowerShell Snap-In in an open PowerShell command window, you can execute the IISConsole.psc1 file from the PowerShell command line:

& "$env:programfiles\IIS\PowerShellSnapin\iisConsole.psc1" 

The $env object is a PowerShell environment variable that contains information about the local machine.

You only need to install and register the IIS PowerShell Snap-In once. After that, you can simply open it by clicking the IIS PowerShell Management Console shortcut on the Start menu, using the Run as administrator option if necessary.

Getting the Snap-In Running on Server 2008 R2 and Windows 7

You don't need to install and register the IIS PowerShell Snap-In if you're running Server 2008 R2 or Windows 7 because IIS 7.5 already includes it. However, you need to import the IIS WebAdministration module.

There isn't an IIS PowerShell Management Console shortcut on Server 2008 R2 or Windows 7, so you begin by opening PowerShell. For example, if you have PowerShell 1.0, you'd select All Programs from the Start menu, choose Windows PowerShell 1.0, and click Windows PowerShell. Next, you need to run two commands in the PowerShell console. First, run the following command to import the IIS WebAdministration module:

Import-Module WebAdministration 

Then, run this command to navigate to the IIS namespace:

Set-Location IIS:\ 

You need to run these two commands every time you want to use the IIS PowerShell Snap-In because the Import-Module cmdlet imports modules only to the current session in PowerShell 2.0 and earlier. If you want to avoid this hassle, you can create your own shortcut for the IIS PowerShell Snap-In. Simply create a shortcut on the desktop (or another location) and set its target to C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psconsolefile "C:\Program Files\IIS\PowerShellSnapin\IIsConsole.psc1" -NoExit -command set-location IIS:\;clear-host\.

Getting Familiar with the Cmdlets

The IIS PowerShell Snap-In is really a collection of cmdlets for managing the IIS server. They provide control over pretty much every facet of IIS, including websites, web applications, application pools, virtual directories, and .NET application domains. The snap-in cmdlets can be grouped into three categories:

  • Cmdlets required by the provider's namespace hierarchy
  • Low-level configuration cmdlets
  • Task-based cmdlets

Cmdlets required by the provider's namespace hierarchy. A hierarchical namespace is a lot like a file system in that it's comprised of directories that contain files and other directories, except that in this case, data stores are being exposed in a hierarchical fashion. Underneath the base IIS:\ namespace, configuration properties are organized into the following predefined child containers, which can't be deleted or moved:

  • Sites
  • Site Collection
  • Applications and Virtual Directories
  • AppPools
  • WorkerProcesses
  • SslBindings

The Set-Location and Get-ChildItem cmdlets can be used to navigate between these containers. Specialized cmdlets such as New-Item, Set-ItemProperty, and Get-WebFilePath are used to work with each namespace's configuration properties. For example, issuing the Get-ChildItem command from the IIS:\ namespace will list all the child containers that have been created, as Figure 2 shows.

Listing the Containers Using the Get-ChildItem Command

Low-level configuration cmdlets. Every one of IIS's hundreds of configuration settings can be set using configuration cmdlets. Moreover, these cmdlets work against your own custom configuration sections. A few examples of configuration cmdlets include Add-WebConfiguration, Add-WebConfigurationProperty, Get-WebConfiguration, SetWebConfiguration, and Restart-WebItem.

Task-based cmdlets. These cmdlets are for daily IIS tasks such as creating websites, enabling request tracing, and adding a handler or a module. Examples of task-based cmdlets include Add-Content, Add-History, and Add-Member. You can retrieve the full list of cmdlets using the command:

Get-Command -module WebAdministration

If you want to get help on how to use an IIS-specific cmdlet, you can use the Get-Help cmdlet with the name of the cmdlet:

Get-Help

For example, Figure 3 shows the results of using Get-Help to see the usage information for the Get-WebConfiguration cmdlet. As the Help information notes, you can add the -detailed flag to get even more information on input parameters and some examples. If you add the -full flag, you'll get everything on the subject.

Using Get-Help to Get Usage Information for the Get-WebConfiguration Cmdlet

Now that you're familiar with the type of cmdlets available in the IIS PowerShell Snap-In and how to get more information about them, I'll walk you through several examples of how to use them. I'll show you how to use the cmdlets to work with websites, fetch content from the IIS server, back up and restore web content and configurations, and set configuration redirection properties.

Working with Websites

Websites are located within the Sites container. To view all the websites on the server, you need to use the Get-ChildItem cmdlet. First, navigate to the Sites folder, using the command:

Set-Location Sites

From there, you can use the Get-ChildItem cmdlet to get a complete list of the installed websites, as Figure 4 shows. In this case, there's only the Default Web Site.

Getting a Complete List of the Installed Websites

If you want to add a website, you can use the New-Item cmdlet. Besides specifying the website's namespace, you include the -physicalPath and -bindings parameters. For example, here's how you would create a new website named MySite:

New-Item iis:\Sites\MySite -bindings `
  @{protocol="http";bindingInformation=":80:MySite"} `
  -physicalPath c:\inetpub\wwwroot\mysite 

The -bindings parameter's @{} hashtable includes the protocol, port, and root folder. It sets the attributes within the IIS site's bindings section:



Deleting a website is even easier. You just need to use the Remove-Item cmdlet with the website's namespace as a parameter. Here's how you'd delete the site just created:

Remove-Item iis:\sites\MySite 

However, don't do that just yet. Instead, let's add a web application, application pool, and two virtual directories. To create a web application, you use the New-Item cmdlet again, but this time you use the -type parameter instead of the -bindings parameter. You set the -type parameter to Application, as shown here:

New-Item 'IIS:\Sites\MySite\DemoApp' `
  -physicalPath C:\inetpub\wwwroot\DemoApp `
  -type Application

To create an application pool, you just need to use the New-Item cmdlet with the application pool's namespace:

New-Item IIS:\AppPools\DemoAppPool

To create a virtual directory, you use the New-Item cmdlet with the -type flag set to VirtualDirectory. For example, to create a virtual directory in the Default Web Site, you'd use:

New-Item 'IIS:\Sites\DemoVirtualDir1' `
  -type VirtualDirectory `
  -physicalPath C:\inetpub\wwwroot\virtualDirectory1

Similarly, to create a virtual directory for your web application, you'd run:

New-Item 'IIS:\Sites\MySite\DemoVirtualDir2' `
  -type VirtualDirectory –physicalPath `
  C:\inetpub\wwwroot\DemoApp\virtualDirectory2

After your new website is in place, you can create the physical directories and copy files over as required. As Listing 1 shows, you use the New-Item cmdlet with the -type parameter set to Directory to create the physical directories. To copy the files over, you can use the Set-Content cmdlet (if you want to replace the existing content) or the Add-Content cmdlet (if you want to append the content).

Listing 1: Commands to Create Physical Directories and Copy Content to Them
New-Item C:\inetpub\wwwroot\mysite –type Directory
New-Item C:\inetpub\wwwroot\DemoApp –type Directory
New-Item C:\inetpub\wwwroot\virtualDirectory1 `
  -type Directory
Set-Content C:\inetpub\wwwroot\DemoApp\default.htm `
  "DemoSite Default Page"
New-Item C:\inetpub\wwwroot\DemoApp\virtualDirectory2 `
  -type Directory
Set-Content `
  C:\inetpub\wwwroot\DemoApp\virtualDirectory2\default.htm `
  "Virtual Directory 2 Default Page"

Fetching Content from the Server

Because PowerShell has access to all .NET classes, you can request content from the IIS server using the .NET WebClient classes in PowerShell commands. For example, you can request content to make sure that your website and web applications work. Figure 5 shows the results of a command requesting the content of the default page for the web application (Demo App) created previously.

Requesting the Default Page Content for Demo App

That's one way to make sure that your website and web applications work. Another way is to view them in a browser. For example, to view the default page for Demo App, you'd run:

$ie = New-Object -com "InternetExplorer.Application"
$ie.navigate("http://localhost/demoapp/default.htm")
$ie.visible = $true 

Figure 6 shows the results.

Using a Browser to View Demo App's Default Page

If you enjoy one-liners, the following command will open Demo App in the default browser:

(New-Object -Com Shell.Application).Open `
  ("http://localhost/demoapp/default.htm")

Backing Up Web Content and Configurations

It's important to regularly back up your IIS content and configurations so that you're prepared in the event that you have to perform disaster recovery or reconfigure your servers. To back up your content and configurations, you can use the AppCmd utility or the Backup-WebConfiguration cmdlet.

AppCmd. To use the AppCmd utility for backups, you need to follow the command syntax:

appcmd.exe backup ""

where is the action to perform (e.g., add, list) and is the name of the backup folder. If the folder name contains spaces, it must be in quotes. To perform a backup, you use the add action. For example, here's how to call AppCmd with the add action in the PowerShell console:

& $env:windir\system32\inetsrv\appcmd.exe `
  add backup "My Backup"

The ampersand (&) at the start of the line is the invocation operator. It's useful for invoking an executable that has spaces in it and for capturing the output of a command-line application like AppCmd.

If you don't include a name for the backup folder, AppCmd will create one using a date/time format. For more control over formatting, it's better to obtain the date using the Get-Date cmdlet. In the following example, the date is appended to the label Backup and formatted to yyyy-MM-dd using the -f flag. To concatenate the label and date, Get-Date is enclosed in $() to create a subexpression and the entire name parameter is enclosed in double quotes:

& $env:windir\system32\inetsrv\appcmd.exe `
  add backup "Backup $(get-date -f yyyy-MM-dd)"

If you ran this command on April 4, 2013, for example, the backup folder would be named Backup 2013-04-04.

If you want a list of available backups, you can run AppCmd with the list action, as Figure 7 shows. Note that the nine backups starting with CFGHISTORY were created by the IIS Configuration History feature. Introduced in IIS 6, it acts as a safety net by running a service that monitors the master configuration file, ApplicationHost.config, for changes. Periodically, it creates snapshots that can be retrieved if a problem arises.

Using the AppCmd Utility Within PowerShell to List the Available Backups

Backup-WebConfiguration. This cmdlet replaces the Windows Script Host (WSH) iisback.vbs script. It accepts a -name parameter that designates the name for the backup folder:

Backup-WebConfiguration -Name "My Backup"

Once again, if the folder name contains spaces, it must be in quotes.

To get a list of the available backups, you can use the Get-WebConfigurationBackup cmdlet. Unlike AppCmd, Get-WebConfigurationBackup returns the folder names with a timestamp specifying when the folders were created, as Figure 8 shows.

Using the Get-WebConfigurationBackup Cmdlet to List the Available Backups

Another way of viewing the available backups it to run:

explorer $env:windir\system32\inetsrv\backup

This command will open the backup root folder in Windows Explorer, as Figure 9 shows. From there, you can browse through the available backups.

Browsing Through the Available Backups in Windows Explorer

Restoring Web Content and Configurations

You can use either the AppCmd utility or the Restore-WebConfiguration cmdlet to restore IIS content and configurations from a backup. For example, to restore the configurations from My Backup using AppCmd, you'd run:

& $env:windir\system32\inetsrv\appcmd.exe `
  restore backup "My Backup"

The command to execute when using Restore-WebConfiguration is:

Restore-WebConfiguration -Name "My Backup"

To delete that backup using AppCmd, you'd run:

& $env:windir\system32\inetsrv\appcmd.exe `
  delete backup "My Backup"

The Remove-WebConfigurationBackup cmdlet lets you achieve the same result:

Remove-WebConfigurationBackup –Name "My Backup"

Setting Configuration Redirection Properties

Redirection is one way to make sure that users always receive the web page they want. The term redirection refers to the process of configuring the web server to issue a redirect message to the browser so that it resubmits a request for the new location. This is useful when your site is under construction or the domain name has changed. You can redirect users to another file, directory, or site.

Although you can manually set the redirection properties in the \%SystemRoot%\System32\inetsrv\config\redirection.config file, it's much easier to use the PowerShell Microsoft.Web.Administration.ServerManager class. In redirection, the destination page is relative to the requested one. For example, if you configure the redirection destination to http://www.mysite.com/sales.aspx and an incoming request is for http://www.mysite.com/marketing/default.aspx, IIS will redirect the request to http://www.mysite.com/sales/default.aspx. Listing 2 contains a short script that sets the redirection path and enables redirection.

Listing 2: Script to Set a Redirection Path and Enable Redirection
[System.Reflection.Assembly]::LoadFrom( `
  "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" )
$serverManager = `
  New-Object Microsoft.Web.Administration.ServerManager
$config = $serverManager.GetRedirectionConfiguration()
$redirectionSection = `
  $config.GetSection("configurationRedirection")

$redirectionSection.Attributes["enabled"].Value = "true"
$redirectionSection.Attributes["path"].Value = `
  "\\MyServer\configFiles"

$serverManager.CommitChanges()

Automating Web Deployments

Before going through the trouble of writing web deployment scripts from scratch, you should take a look at Web Deploy 3.0. Microsoft created this free tool to simplify migrating, managing, and deploying web applications, sites, and servers.

Web Deploy includes four useful PowerShell scripts:

  • SetupSiteForPublish.ps1
  • CreateSqlDatabase.ps1
  • CreateMySqlDatabase.ps1
  • AddDelegationRules.ps1

They can help you with all kinds of tasks, such as packaging websites, automatically including content, making configurations, creating databases, synchronizing IIS 6 and IIS 7, and migrating from IIS 6 to IIS 7.

For example, you can run SetupSiteForPublish.ps1 without arguments to create a default publishing website without databases. You just run the following commands:

Set-Location `
  C:\Program Files\IIS\Microsoft Web Deploy v2\Scripts
.\ SetupSiteForPublish.ps1

The script creates a site named WDeploySite with physical site root at \%systemdrive%\inetpub\WDeploySite. The site will have a matching application pool named WDeployAppPool, which will be assigned to port 8080 by default. The script also creates a non-administrative local Windows user named WdeploySiteuser. The settings information is then saved to the desktop in the file WDeploy.PublishSettings.

If you want to enable publishing for a new user on a new site as well as provide a name and location for the .PublishSettings file, you invoke the script as follows:

.\SetupSiteForPublish.ps1 -siteName MySite `
  -sitePhysicalPath C:\inetpub\wwwroot\MySite `
  -siteAppPoolName MySitePool -sitePort 8080 `
  -deploymentUserName MySiteUser `
  -deploymentUserPassword Password01 `
  -publishSettingSavePath C:\profiles `
  -publishSettingFileName MySite.PublishSettings

For more information about using the PowerShell scripts included with Web Deploy, see "PowerShell scripts for automating Web Deploy setup." For information about how to set up Web Deploy, see "Installing and Configuring Web Deploy."

Get Acquainted with the IIS PowerShell Snap-In

I've shown you just a sampling of the tasks that can be performed using the IIS PowerShell Snap-In. You can use these examples as a starting point for getting acquainted with this exceptional automation tool. For more information about using PowerShell to automate IIS 7, see "An Introduction to Windows PowerShell and IIS 7.0."