Nuts and Bolts PowerShell Lead image: © Olexandr Moroz, 123RF.com
© Olexandr Moroz, 123RF.com
 

PowerShell for Exchange and SharePoint

Power Package

Microsoft offers PowerShell extensions for Exchange and SharePoint to let administrators manage these server products at the command line. In fact, some settings can only be implemented in the PowerShell extension. By Thomas Joos

Using PowerShell isn't all that complex. You can just type get-command to list the available commands. Very few administrators will be familiar with the full set of command-lets (cmdlets) and options that Exchange Server 2010 provides, but the management shell has a comprehensive help function to get more information.

If you can remember part of the command, you can use the * wildcard. For example, get-command *mailbox gives you a complete list of cmdlets that end in "mailbox." If the command you are looking for isn't part of the list, you can also use multiple placeholders (e.g., get-command *mailbox*), which lists all commands in which the word "mailbox" occurs.

Calling for Help

Once you have found the required cmdlets, PowerShell will support you with more options. For just about any cmdlet, you can assume that four variants exist: Cmdlets that start with the new- prefix are used to create something (e.g., new-mailbox). Deletions are done with remove- (e.g., remove-mailbox), the set- prefix modifies an object (e.g., set-mailbox), and the get- prefix retrieves a value (e.g., get-mailbox).

Of course, you can use many other cmdlets besides these – for example, start and stop or import and export. If you just enter the cmdlet, either nothing happens or you are asked to identify the object. For example, the get-mailbox cmdlet lists all mailboxes in an organization. The help cmdlet command displays help text for a specific cmdlet.

A help cmdlet -detailed option exists for many cmdlets, and it displays more detailed information. The combination help cmdlet -examples lists usage examples for the command and works for the commands in the management shell, too. Use get-cmdlet to display information for objects; the |fl command formats the output. If you don't want a full set of information but just want to display individual parameters, you can list the parameters following the |fl option. For example, if you just want to see the display name, the database, the alias, and the organizational unit for the user@contoso.com mail account, enter the command:

get-mailbox user@contoso.com |fl display name, database, alias, organizationalunit

Cmdlets are not case sensitive. If you run a wizard in the Exchange management console, the wizard shows you the corresponding PowerShell command when it terminates; you can then copy the command to use it for additional actions (Figure 1). On the basis of the given command, you can probably derive the syntax for handling a few tasks in PowerShell in the future, instead of turning to a graphical interface.

In the Exchange management console, you always see the corresponding Exchange management shell command at the end.
Figure 1: In the Exchange management console, you always see the corresponding Exchange management shell command at the end.

If you make some changes in the Exchange management console, the icon for the Exchange management shell will appear in the bottom left corner in every window (see Figure 2). The command shown in the figure is a new function in Exchange Server 2010.

Displaying the command for the management shell in the Exchange management console.
Figure 2: Displaying the command for the management shell in the Exchange management console.

If you click the View menu in the Exchange management console and then select Show control protocol for Exchange management shell, you can enable logging in the new window via Action/Start command logging. If you make changes in the Exchange management console, the console stores the corresponding commands for the management shell. You can also use PowerShell to output all of the Exchange databases that exist on your company's servers. To do so, type get-mailboxdatabase. This command returns a formatted list of all mailbox databases. The dismount-database command lets you unmount the database at the command line; you simply need to pass in the name of the database.

If you change this command from dismount-database to mount-database, you can mount the database again. You will not see a message that the database has been mounted; however, if you press F5 in the Exchange management console, you will see that the status of the database has changed back to ready.

In the Exchange management shell, you can also read the mailboxes within a mailbox storage database. Type get-mailbox to see a list of all the mailboxes in your organization. You will also see the servers on which the individual mailboxes reside and see whether the limit is set to prevent sending. The following command displays the mailboxes sorted by mailbox database and display name:

get-mailbox | format-table displayname, database

On Exchange Server 2007, the move-mailbox command would move mailboxes between mailbox storage databases in the management shell. Exchange Server 2010 uses the New-MoveRequest, Get-MoveRequest, Remove-MoveRequest commands for this. You can also run:

get-mailbox -database Mailbox | move-mailbox -targetdatabase Mailbox Database

to move mailboxes from the Mailbox database to the Mailbox Database database. You will be prompted to confirm the move, after which, the Exchange Server will launch the process. The command

get-mailbox -database Mailbox | move-mailbox -targetdatabase Mailbox Database -validateonly

doesn't tell Exchange to move the mailboxes; it simply checks to see whether the move is possible and outputs a comprehensive information screen telling you which options will be performed if you do not specify the -validateonly option.

Another option in this context is -whatif, which works like -validateonly but is less verbose. Regardless of the options you choose, you are given comprehensive details of what Exchange would do or has done. In other words, you can pipe the data that get-cmdlets retrieved directly to the processing cmdlets.

The Exchange management shell not only lets you access properties within Exchange, but you can also access Active Directory directly. You can create groups, configure group memberships, and so on. In the Exchange management shell, you can also retrieve statistics concerning the mailboxes in your organization. For example, if you enter the command get-mailboxstatistics, you are shown detailed information about the individual mailboxes within the Exchange organization. The get-mailboxstatistics | group database command outputs statistics grouped by the individual mailbox databases.

PowerShell Goes SharePoint

SharePoint now also has a PowerShell extension. In addition to the SharePoint 2011 management shell, SharePoint Server 2010 also has a command-line tool called stsadm.exe in the %COMMONPROGRAMFILES%\Microsoft Shared\Web server extensions\14\Bin directory. The tool is very rarely used in SharePoint Server 2010 because the SharePoint management shell has taken over its tasks.

If you want to use PowerShell commands in SharePoint 2010, you first need to launch the management shell via the SharePoint program group or load the commands into a normal PowerShell. To do so, type the following in PowerShell or PowerShell ISE:

Add-PSSnapin Microsoft.SharePoint.Powershell

The following command

gcm -pssnapin microsoft.sharepoint.Powershell | select name, definition | fl > .\SP2010cmdlets.txt

will create a text file containing all the cmdlets for SharePoint. The options for displaying the help and syntax mentioned previously also apply to the SharePoint management shell. You can display the solutions of the farm by typing Get-SPSolution, install new ones by typing Add-SPSolution WSP-File, and display features by typing Get-SPFeature.

Instead of installing SharePoint Server 2010 in the traditional way, you can also handle the installation entirely in PowerShell. To do this, you need the PowerShell extension from the SPModule.zip archive, which is a PowerShell extension with additional commands for SharePoint. The SharePoint developers have posted the archive online [1]. Download the ZIP file from the website and unpack the archive. After doing so, you will find two subfolders: SPModule.misc and SPModule.setup. These two folders contain the scripts you need to handle the installation in the PowerShell.

The next step is to configure PowerShell so it can use the SharePoint scripts. To do this, add the folder with the subdirectories SPModule.misc and SPModule.setup to the PowerShell input path. If you don't, you need to enter every single command from these two directories with its full path in PowerShell. To list the current paths from which PowerShell accepts commands, type $env:PSModulePath. The following command extends the path:

$env:PSModulePath = $env:PSModulePath + New-Path

That said, the easiest solution is to copy the SPModule.misc and SPModule.setup folders directly into the C:\Windows\System32\WindowsPowershell\v1.0\Modules directory.

This is the path where the other PowerShell modules reside. If you want to reserve SharePoint for use by the current user only, copy the folders into the C:\Users\<Username>\Documents\WindowsPowershell\Modules directory instead.

After adding the modules to the path, or copying them, you still need to add the command to PowerShell. The scripts for SharePoint are not signed, however, so the shell will output an error message when you attempt to load the commands.

By default, Windows PowerShell will block unsigned scripts because of execution policy; however, you can change the execution policy using the Set-ExecutionPolicy cmdlet and display the execution policy using get-executionpolicy. The execution policy stores its data in the Windows registry. You can change the following settings:

After entering Set-ExecutionPolicy unrestricted, you still need to confirm execution. Then, execute Import-Module SPModule.misc to import the first extension into PowerShell (Figure 3).

Configuring PowerShell to support SharePoint Server 2010.
Figure 3: Configuring PowerShell to support SharePoint Server 2010.

The next step is to load the commands required for the installation by typing Import-Module SPModule.setup. If you want to install SharePoint Server 2010 remotely via PowerShell, check out the installation guide [2], which has more detailed information on this topic.

The important commands during the installation of SharePoint Server 2010 in PowerShell are the following three cmdlets: install-sharepoint, new-sharepointfarm, and join-shrepointfarm.

To complete the installation in PowerShell, you also need appropriate XML response files. The files are available on the SharePoint Server 2010 DVD in the \Files directory. With these response files, you can automate the process of installing and configuring SharePoint. You can now launch the installation by typing:

Install-SharePoint -SetupExePath Setup.exe -ConfigXmlPath XML-File

You can copy the XML file to any location and modify the file to reflect your own needs. Microsoft recommends using Notepad to modify XML files.

For example, if you want to add the product key to the XML file, add the path <PIDKEY Value="Product_key" /> to a file. If you want to perform the installation in PowerShell without using an XML file, you can control the server options directly using the Install-SharePoint cmdlet.

The following command is used for a standalone server:

Install-SharePoint -SetupExePath Setup.exe -PIDKey "Productkey" -ServerRole "SINGLESERVER"

And the command looks like this for a farm server:

Install-SharePoint -SetupExePath Setup.exe -PIDKey "Productkey"

The -PIDKey option works with the XML file approach or for direct imports of the server type. You can download the free SharePoint 2010 PowerShell Scripts & Utilities [3], load them as a PowerShell module, and generate the installation packages, or you can install the SharePoint 2010 prerequisites.

Get-SPPrerequisites lets you install the prerequisites in PowerShell (Figure 4). For this to happen, the server needs an Internet connection. New-SPInstallPackage generates installation packages and response files, as well as batch files that let you automate the installation of SharePoint 2010. Install-SPIFilter installs third-party iFilters and configures the search accordingly. The download page also has a comprehensive guide for the tools.

Using the SharePoint 2010 PowerShell Scripts & Utilities.
Figure 4: Using the SharePoint 2010 PowerShell Scripts & Utilities.

For the installation, you first need to copy the SPInstallUtils module file into a directory on the server. To use the commands, you need to import the module into PowerShell using import-module path. Help is also available for all these tools.

Besides installing the required server roles in PowerShell and provisioning servers with SharePoint Server 2010 by means of PowerShell extensions, you also can execute the configuration wizard for SharePoint products in PowerShell. If you want to create a new server farm, you can use the New-SharePointFarm cmdlet. If you omit the -FarmName option, the command creates a standalone installation. The Join-SharePointFarm cmdlet lets you join a server farm.

The New-SPWebApplication cmdlet creates new web applications in PowerShell. Table 1 lists the syntax for the various commands. New collections of websites are created with the New-SPSite cmdlet. The standard services for SharePoint are installed with Install-SPService.

Tabelle 1: Installation Options

Function

Syntax

New server farm

New-SharePointFarm -DatabaseServer server_name -DatabaseAccessAccount username -FarmName farm_name

New server farm with Get-Credential

New-SharePointFarm -DatabaseAccessAccount (Get-Credential Domain\username) -DatabaseServer server_name> -FarmName FarmName

Standalone installation

New-SharePointFarm -DatabaseServer server_name -DatabaseAccessAccount username

Join a farm

Join-SharePointFarm -DatabaseServer server_name -DatabaseName database -Passphrase passphrase_for_farm

New web application

New-SPWebApplication -Name Name -ApplicationPoolAccount (Get-SPManagedAccount Domain\username)

New website collection

New-SPSite URL -OwnerAlias Domain\username

To install all of the available SharePoint features, you can run the Install-SPFeature -AllExistingFeatures cmdlet. The Get-SPFarm | select Servers cmdlet lists all the servers on a farm.

Conclusions

The extensions for Exchange and Small Business Server introduced here allow Windows admins to leverage the maximum potential of PowerShell. This functionality turns the Windows server with its often criticized point-and-click interface into a tool that bears comparison with the Unix command line.