Microsoft Press: Using Windows PowerShell to Perform and Automate Farm Administrative Tasks

SharePoint 2010

Applies to: SharePoint Server 2010

Topic Last Modified: 2012-04-26

This book excerpt is from Microsoft SharePoint 2010 Administrator's Companion, Microsoft Press, August 2010.

Buy this book

This excerpt from Microsoft SharePoint 2010 Administrator's Companion explores the SharePoint 2010 Management Shell and how to use Windows PowerShell to accomplish some basic administrative tasks.

Bill English

Bill English, MCTS, MCT, CTT+, GSEC certified, is a Microsoft® MVP for SharePoint® Server. He runs a leading training and consulting company, has written 10+ books, and speaks at the Microsoft® Office SharePoint® Conference, Comdex, and other events.

Brian Alderman

Brian Alderman has his master's in Computer Information Systems and is currently employed by Mindsharp which is located in the Minneapolis-St. Paul area of Minnesota. Since 1995, he has held several Microsoft certifications that currently include; MCT, MCTS for SharePoint, MCITP for SQL Server®, MCSA and MCSE for Windows Server®, and also his PMP certification. As a Senior Technical Instructor and Consultant he has nearly 15 years of experience in networking, SQL Server databases, SharePoint technologies, and project management. Brian's previous publications include Windows 2000 Professional and SQL Server 2000 Administration. He is an active speaker at SharePoint Industry conferences including SharePoint Saturday's and the SharePoint Best Practices Conference.

Mark Ferraz

Mark Ferraz is the President of SolutionsMark (, a Houston-based consulting firm specializing in the design, development, and implementation of enterprise platforms, solutions, and services based on Microsoft SharePoint Products and Technologies. As a Senior Information Architect, Enterprise Network/Systems Architect, and Developer, Mark has over ten years of experience designing, managing, and implementing complex projects for some of the world's largest companies. In addition to being a contributing author of Microsoft Office SharePoint Server 2007 Best Practices, Mark is an active speaker at industry conferences such as SharePoint Best Practices Conference and SharePoint Technology Conference.

Over the last couple of years, some SharePoint administrators have recognized the power of Windows PowerShell and have tried to use it, but with no built-in support, most administrators have found it too difficult. Microsoft SharePoint Foundation 2010 and Microsoft SharePoint 2010 now contain native support for Windows PowerShell with the SharePoint 2010 Management Shell. This chapter explores the SharePoint 2010 Management Shell and how to use Windows PowerShell to accomplish some basic administrative tasks. Chapter 12, "Using Windows PowerShell to Manage Search Services and FAST Search," builds on the information in this chapter, using search administrative tasks and scenarios.

There is an enormous amount of information available about Windows PowerShell on the Internet and published in books. The aim of this chapter is not to teach you Windows PowerShell, but to show you how to become familiar with the new Windows PowerShell cmdlets, pronounced command-lets, introduced in SharePoint 2010. However, for those who are relatively new to Windows PowerShell, this chapter begins by reviewing the basics.

Traditionally, administrating a server on which Microsoft products are installed has involved learning a number of administrator tools, such as graphical interfaces based on the Microsoft Management Console (MMC), known as MMC snap-ins; many command-line utilities; and perhaps a Windows Management Instrumentation (WMI) provider or Component Object Model (COM) objects that administrators can interface with using VBScript. Until the release of SharePoint 2010, SharePoint Products and Technologies were no different than other Microsoft products in the number of available administrator tools. Administrators needed to rely on the Central Administration website, the SharePoint Products Configuration Wizard, and the command-line tools stsadm and psconfig. No one tool could do everything.

Each Microsoft product also had its own community, which created or extended the built-in tools to make an administrator's life easier. The tools an administrator needed were available, but they were scattered among many sources. This is all changing now that every administrative task can potentially be scripted or automated using Windows PowerShell.

The concept for Windows PowerShell is based on a study commissioned by Microsoft in the early 2000s. Originally based on the POSIX shell as specified in IEEE 1003.2 and influenced by Perl and UNIX shell, Windows PowerShell is a command shell and scripting language that is far more powerful than using the Windows command prompt (cmd.exe). Administrators love command-line tools because they can be batched together to automate repetitive tasks or to ensure that a set of tasks are completed again exactly as they were the last time they were executed. Windows PowerShell cmdlets offer administrators these same benefits. You can still use the traditional tools, but Windows PowerShell adds flexibility and breadth that the traditional tools do not provide.

Community-led initiatives for previous versions of SharePoint include extensions to stsadm, published at; Windows PowerShell scripts for Windows SharePoint Services 3.0 and Microsoft Office SharePoint Server 2007 that can be found at; and the CodePlex project "PowerShell SharePoint Provider" for Windows SharePoint Services 2.0 and Microsoft SharePoint Portal Server 2003, available at

This section covers the following Windows PowerShell topics.

  • What's new in the Windows PowerShell 2.0 release

  • Architecture

  • Installing Windows PowerShell

  • Remote management

Windows PowerShell 2.0 offers a number of new features and improvements from Windows PowerShell 1.0, including

  • New cmdlets

  • Remote Management and background jobs

  • Windows PowerShell Integrated Scripting Environment (ISE)

  • Windows PowerShell debugger

  • Modules

  • Advanced functions

  • Transactions

  • Steppable pipelines

  • Events

  • Script internationalization

  • Online Help

As an IT professional, many of these new features will interest you. For example, you can remotely manage all the servers in your farm from your desktop, and when you become competent in Windows PowerShell, you will be able to create your own advanced functions using the Windows PowerShell scripting language that you can then use as cmdlets. In Windows PowerShell 1.0, the only way to do this was with a developer, using code and deploying files onto your farm.

For more information about what's new in Windows PowerShell 2.0, see What's New in Windows PowerShell and Other resources can be found by using your favorite Internet search engine and entering the keywords What's New in Windows PowerShell 2.0 or the feature names listed previously.

Why is Windows PowerShell so important? Windows PowerShell scripting language is object orientated, built on top of the .NET Framework—.NET Framework 3.5 for Windows PowerShell 2.0—and based on the C# (pronounced C-sharp) programming language. This allows Windows PowerShell to access the underlying object models, to pass objects and their values (properties) from one Windows PowerShell command to another. This means you have almost the power of a developer without having to write, compile, and deploy code. The disadvantage is that it can be all too easy to cause havoc in your installation.

When the Microsoft product teams consider the tools they want to provide to administrators, they build them first on Windows PowerShell. Hence, with the installation of SharePoint 2010, a large number of administrative tasks can be completed natively with Windows PowerShell cmdlets, with no need to install software from community-led initiatives. If any additional cmdlets are required, you can create them using Windows PowerShell scripts and the Advanced Functions feature in Windows PowerShell 2.0, and developers within your organization can create new cmdlets. Using Windows PowerShell to help administer SharePoint is the way of the future, so it's important to start learning to use the built-in cmdlets as soon as possible.

At first, using Windows PowerShell may seem daunting, but if you have used the command prompt (cmd.exe) or have created batch files, you will soon be comfortable with the Windows PowerShell console. In fact, you can even use the Windows PowerShell console instead of the command prompt, because all the commands you currently use, such as dir, cd, and ping, work equally well in the Windows PowerShell console as they do in the command prompt. You may need to enclose command-line parameters in quotation marks to use the commands from within Windows PowerShell, but that is about the only modification you need to make. So there is no need to use two different windows to complete your administrative tasks.

By default, the command prompt has a black background, but this can be changed. Right-click the title bar and then select Properties. A Properties dialog box appears with four tabs: Options, Font, Layout, and Colors. You can change the font, background color, window size, and more. See the sidebar titled "Command-line Shortcuts" later in this chapter for more information about similarities between the two command-line interfaces.

There are two ways of using Windows PowerShell: either through a command-line interface, known as the Windows PowerShell console (powershell.exe), or through the Windows PowerShell Interactive Scripting Environment (ISE) graphical interface (Powershell_ise.exe). This chapter concentrates on using the Windows PowerShell console.

Following are some resources for more information on Windows PowerShell.

All the same shortcuts that you use at the command prompt work in the Windows PowerShell console.

  • To pause the display temporarily when a command is writing output, press Ctrl+S, and then press Ctrl+S to resume or press Ctrl+C to terminate execution.

  • By default, up to 50 commands are stored in a buffer. You can move through the buffer by using the up arrow and down arrow keys to scroll through the commands so you can easily execute the next or a previous command.

  • The buffered commands can be displayed from a pop-up window by pressing F7. Select the command you want to execute using the arrow keys, press Enter or F9, type the number of the command you want to execute, and then press Enter.

  • The buffered commands can be displayed from the command line by typing the first few characters of the command you want and then pressing F8. The command-line interface searches though the history buffer for the first command that begins with the characters you typed.

  • Using the auto completion capabilities of the Windows PowerShell command shell, you never need to type the complete name of a command. Type in the first few characters of the command you want and press Tab to cycle through all commands and available file names and folders in alphabetic order, or click Shift+Tab to cycle through the commands in reverse order.

  • To copy and paste text, right-click the command-line interface title, click Mark, highlight the text you want to copy, and then right-click the window title again to copy the selected text automatically into the Clipboard.

  • Commands are case insensitive and can be batched together and placed in a text file. By calling that file in the command-line window, the commands in the file are executed. These text files have an extension of .bat, .cmd, .vbs, or in the case of Windows PowerShell, .ps1. Commands in these files can be executed outside the command window by calling the file from the Run line or by double-clicking the file in Windows Explorer.

  • Arguments can be sent to the command file being called. The arguments passed to your command file are stored in memory and accessed using variables. You can also create variables to store values needed as you complete a task. In Windows PowerShell, you reference variables by preceding the variable name by a dollar sign ($).

  • Output from a command can be directed to a file named to the right of >. This will overwrite the file if it already exists. To redirect the output but append it to the file, use >>. Error messages that result from running a command can be redirected to a file named to the right of 2>, or they can be appended to a file by using 2>> or sent to the same destination as the standard output by using 2>&1.

  • You can execute many commands on the same line. In Windows PowerShell, you separate commands using the semicolon character (;).

  • Redirect the output of one command as input to another command by separating both command with a '|', known as a pipe. For example, dir | sort | more will display a sorted list of files in the current directory one page at a time. The pipe is the symbol located above the backslash on most keyboards.

  • Aliases and shortcuts can be substituted for commonly used commands. For example, the ForEach-Object cmdlet can be replaced with ForEach or even with the percentage character, %. The question mark character, ?, can be used in place of Where or Where-Object. You can also use Get-Alias to return a list of aliases. Note that the use of aliases in scripts can make them difficult to understand.

  • Examples of these shortcuts can be found throughout this book.

Computers running Windows 7 or Windows 2008 R2 or later include Windows PowerShell 2.0 and Windows Remote Management (WinRM) 2.0. If you want to manage computers using earlier operating systems locally or remotely using Windows PowerShell, you will need to install both Windows PowerShell 2.0 and WinRM 2.0.

A copy of Windows PowerShell 2.0, together with WinRM 2.0, can be downloaded from Ensure that you obtain the correct version; for example, if you install SharePoint on the 64-bit version of Windows Server 2008, you need to download and install the Windows 2008 x64 version of Windows PowerShell 2.0 and WinRM 2.0. After they are installed, you will find the executable for the Windows PowerShell ISE in the folder %SystemRoot%\System32\WindowsPowerShell\v1.0.

If you going to be a heavy user of ISE, consider placing a shortcut for this program on your taskbar. On the Start menu, right-click Powershell_ise.exe and then select either Pin To Taskbar or Pin To Start Menu.

To use Windows PowerShell ISE on Windows 2008 R2, you need to add the Windows PowerShell ISE feature. This feature can be added using Windows PowerShell commands or the Server Manager. After you have installed SharePoint 2010 or SharePoint Foundation 2010, perform the following steps.

  • Using Windows PowerShell, enter the following commands.

    Import-Module Servermanager; Add-WindowsFeature "PowerShell-ISE"

  • Using Server Manager, complete the following procedure.

    1. Start the Server Manager, click Features, and then select Add Features.

    2. In the middle pane of the Add Features Wizard, select the check box for Windows PowerShell Integrated Scripting Environment (ISE) as shown in Figure 5-1 and then click Next.

Installing Windows PowerShell

Figure 5-1 Install the Windows PowerShell Integrated Scripting Environment (ISE) feature

  1. On the Confirmation Installation Selection screen, click Install.

  2. On the Installation Results screen, click Close.

Windows PowerShell is a powerful tool, and as with any other scripting language, it is all too easy to borrow someone else's code or download snippets from the Internet. Also, because the code files are just text files, it is easy for anyone to modify them and inject malicious code. Therefore, Windows PowerShell has a built-in security feature called execution policy that you can set on a per-user basis, and these settings are saved in the registry. To view your execution policy, type the following command in the Microsoft SharePoint 2010 Management Shell.

If you are running the Management Shell on a SharePoint server, it is likely that the output from such a command is RemoteSigned, which means that you can run any commands interactively and you can use any scripts that are stored on the computer where you are logged in. However, if you want to run configuration files or scripts from remote sources, they need to be signed. You can change the execution policy if you start the Windows PowerShell console as an administrator and use the Set-ExecutionPolicy cmdlet, or you can change the registry key as follows.


securitySecurity Note
The registry key is useful in conjunction with an Active Directory Group Policy. Manual modifications to the registry should be avoided, especially when Microsoft provides a cmdlet to configure Windows PowerShell execution policy.

To sign scripts, use the Set-AuthenticodeSignature cmdlet, which can be used to add an Authenticode signature to a Windows PowerShell script or other file.

In an organization that has multiple environments, such as development, system integration, user acceptance test (UAT), pre-production, and production, consider the need to sign code on your production and UAT farms at minimum. You should also review the execution policy settings for these farms. You can set the execution policy in a Group Policy Object that targets either users or computers so that it cannot be overridden when someone logs on to your SharePoint servers.

For more information on Windows PowerShell execution policies and signing scripts, see the TechNet article "Heading Off Malicious Code" at, or type Get-Help about_Execution_Policies at a Windows PowerShell command-line interface. There is also a blog post that explains the process in detail. It is "ALLSigned: Signing Your PowerShell Scripts" and can be found at
If you are using Windows 7 as your desktop and you want to remotely manage Windows Server 2008 R2 for your SharePoint servers, you need the Remote Server Administration Tools (RSAT), which is required for the new Group Policy features and supports Windows PowerShell. RSAT is available from the Microsoft Download Center at For more information, go to and

Windows PowerShell 2.0 introduces a new capability to manage your systems remotely from your desktop by using either WinRM or Internet Information Server (IIS). WinRM is often the mechanism used by administrators and the subject of this section. Remote Management involves not just the ability to run Windows PowerShell locally on your machine using the few commands that allow you to specify a computer name as an optional parameter; it also includes methods known as fan-in and fan-out remoting and background jobs.

  • Fan-in remoting This allows many administrators to connect to an instance of Windows PowerShell running on the same remote servers—this is not supported out of the box in SharePoint 2010.

  • Fan-out remoting This allows you to send a single Windows PowerShell command to run multiple remote instances of Windows PowerShell in parallel, and the results of those commands will be returned to your desktop. You would use this if you need to complete the same task on multiple servers. You no longer need to establish a Remote Desktop connection to each server in turn and then execute the commands locally on that server. You can create a set of Windows PowerShell commands and pass the server names to those commands, which then completes the same commands sequentially for each server whose name you provide.

  • Background jobs Windows PowerShell 2.0 supports both local and remote background jobs. These are commands that execute asynchronously in the background with no interaction. When you execute a command in the background, the command prompt is returned immediately so that you can continue to execute other commands.

The WinRM Windows service must be started and configured for remoting on both your local computer and the server on which you want to remotely run commands. To find out if your server is running WinRM, type

Get-service winrm

To check if it is running on a remote server, type

Get-service winrm -computername $server_name

On your SharePoint server, this service should be running; however, if your local computer is running Windows 7 (or Windows Vista with Windows PowerShell 2.0 and WinRM 2.0 installed), you may need to start this service and enable remoting. You can do this by typing one command, Enable-PSRemoting, which executes two additional commands, Set-WSManQuickConfig and Start-Service WinRM.

If one of the network connection types is Public, the Set-WSManQuickConfig command will raise an Invalid Operation Exception. You will need to change the network connections to the network type of either Domain or Private to proceed.

The output to the Enable-PSRemoting command will look similar to the following example.

WinRM Quick Configuration
Running command "Set-WSManQuickConfig" to enable this machine for remote management
through WinRM service.
 This includes:
    1. Starting or restarting (if already started) the WinRM service
    2. Setting the WinRM service type to auto start
    3. Creating a listener to accept requests on any IP address
    4. Enabling firewall exception for WS-Management traffic (for http only).

Do you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default
is "Y"): y
WinRM has been updated to receive requests.
WinRM service type changed successfully.
WinRM service started.
Configured LocalAccountTokenFilterPolicy to grant administrative rights remotely to local users.
WinRM has been updated for remote management.
Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
WinRM firewall exception enabled.

On a computer running a 64-bit version of Windows, you may see an additional confirmation message.

Are you sure you want to perform this action?
Performing operation "Registering session configuration" on Target "Session
configuration "Microsoft.PowerShell32" is not found. Running command
"Register-PSSessionConfiguration Microsoft.PowerShell32 -processorarchitecture x86 
-force" to create "Microsoft.PowerShell32" session configuration. This will restart
WinRM service.".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

To determine how WinRM is configured, the authentication method, and the port numbers it will access, use the following command.

winrm get winrm/config/service

This should result in an output similar to the following.

    MaxConcurrentOperations = 4294967295
    MaxConcurrentOperationsPerUser = 15
    EnumerationTimeoutms = 60000
    MaxConnections = 25
    MaxPacketRetrievalTimeSeconds = 120
    AllowUnencrypted = false
        Basic = false
        Kerberos = true
        Negotiate = true
        Certificate = false
        CredSSP = false
        CbtHardeningLevel = Relaxed
        HTTP = 5985
        HTTPS = 5986
    IPv4Filter = *
    IPv6Filter = *
    EnableCompatibilityHttpListener = false
    EnableCompatibilityHttpsListener = false

You can run winrm and winrm-related commands, such as the New-PSSession command, from either the Windows PowerShell console or the SharePoint 2010 Management Shell. However, these must be run as an administrator. To do this, right-click the Windows PowerShell console or the SharePoint 2010 Management Shell and then select Run As Administrator. You must be a member of the Administrators group on the remote machine or be able to provide administrator credentials to do this.

When your local computer and the remote computer are in different non-trusted domains or in a workgroup, additional steps are required to configure remoting. The workgroup scenario is likely to occur when SharePoint Foundation is installed for external collaboration or in a small business environment rather than in a typical SharePoint Server installation. For information on how to configure remoting between two workgroup machines, see the blog post at

To use WinRM to execute SharePoint PowerShell cmdlets on a remote machine, there are a number of additional requirements.

  1. You must have access to a userid with the correct rights to execute those commands. These requirements are applicable whether you are remoting into a server or locally executing SharePoint cmdlets. The userid must meet the following criteria.

    • Must be a member of the WSS_ADM_WGP local security group on the machine executing the commands.

    • Must be a member of the SharePoint_Shell_Access SQL Server role on the configuration database.

    • Must have access to the content database that you want to manipulate.

    You can use the SPShellAdmin cmdlets to help you manage these requirements. When you run the Add-SPShellAdmin cmdlet to add a userid to the SharePoint_Shell_Admin role, you must be mapped to Security_Admin role on the SQL instance and the db_owner role to the relevant databases. You need to run the Add-SPShellAdmin cmdlet for each content database that you want the userid to access.

  2. Designate one server in your farm as the server you will always use for remoting. On that server, increase the WinRM configuration option, MaxMemoryPerShellDB, to a large value, 512 or 1024. This configuration option limits the amount of memory a single remote process can use. Increasing the value will allow long-running commands to run without throwing OutOfMemory Exception errors. The command to display the values of the configuration options and sample output is shown here.

    winrm get winrm/config/winrs

        AllowRemoteShellAccess = true
        IdleTimeout = 180000
        MaxConcurrentUsers = 5
        MaxShellRunTime = 2147483647
        MaxProcessesPerShell = 15
        MaxMemoryPerShellMB = 150
        MaxShellsPerUser = 5
     Winrs    AllowRemoteShellAccess = true    IdleTimeout = 180000    MaxConcurrentUsers = 5    MaxShellRunTime = 2147483647    MaxProcessesPerShell = 15    MaxMemoryPerShellMB = 150    MaxShellsPerUser = 5

    To modify the MaxMemoryPerShellDB setting, type the following Windows PowerShell command in the SharePoint 2010 Management Shell.

    Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024

  3. You must use Credential Security Provider (CredSSP) authentication. This authentication mechanism, introduced with Windows Vista, allows an application to delegate the credentials from one machine to another, a process called double hopping. This will enable you to provide the credentials that allow the SharePoint PowerShell cmdlets to talk to the Microsoft SQL Server that is hosting your SharePoint databases. If you do not use CredSSP and you try to remotely execute a SharePoint cmdlet, you are likely to receive a message that indicates the farm is unavailable. In the output from the Winrm get winrm/config/service command shown previously, notice that CredSSP is equal to False. There are several ways you can modify WinRM configuration options, including Group Policy, login scripts, and the command prompt. To enable CredSSP authentication though command-line interfaces, complete the following tasks.

    1. On the computer from which you are remoting, such as your Windows 7 desktop, type the following command, where Web1 is the SharePoint server. Type Y when prompted to confirm that you want to enable CredSSP authentication.

      Enable-WSManCredSSP -role client -DelegateComputer Web1

    2. On the SharePoint server where you are remoting to, type

      Enable-WSManCredSSP -role server

    For more information on multi-hop support in WinRM, see

The commands you need to start a remote session to remotely manage a SharePoint farm or one specific SharePoint server are similar to those in the following example.

$cred = Get-Credential contoso\spfarm
$sess = New-PSSession Web1 -Authentication CredSSP -Credential $cred
Invoke-Command -Session $sess -ScriptBlock '
   {ADD-PSSnapin Microsoft.SharePoint.PowerShell;}
securitySecurity Note
You can limit the Windows PowerShell commands that a user can access during a remote session by using the -ConfigurationName parameter with the New-PSSession cmdlet or by using the Proxy cmdlet. For more information, see the blog post "Extending and/or Modifying Command with Proxies" at

When you enter the first command, a dialog box appears where you must type the password. This password and the user name are stored in the variable $Cred, which is used in the second command, New-PSSession, which establishes a persistent session with the remote server. Creating a persistent session is not necessary when using Windows PowerShell remoting, but if you do not establish a persistent connection, whenever you invoke a remote command that includes a SharePoint cmdlet, each Invoke-Command will also need to include the PSSnapin cmdlet. The third command, Invoke-Command PSSnapin, allows you to run SharePoint PowerShell cmdlets on the remote server.

Reference to the persistent session is stored in the variable $sess. You can direct any commands you want to that remote server by using this variable. In the following example, the cmdlet Get-SPServiceInstance is typed within the script block—the area between the curly brackets ({ }). The output from the Get-SPServiceInstance cmdlet returns the status of the services within a SharePoint farm.

Invoke-Command -Session $s -ScriptBlock {get-SPServiceInstance}

WARNING: column "PSComputerName" does not fit into the display and was removed.

TypeName                         Status   Id
--------                         ------   --
Business Data Connectivity       Online   3ad4d004-9ae3-4810-94bf-76cc43c9d507
Microsoft SharePoint Foundati... Online   81cc6474-fd6f-42ad-a932-25d67cff8cc1
Microsoft SharePoint Foundati... Disabled cb3b976c-b451-4abe-b808-0c6d191ccd3d
Microsoft SharePoint Foundati... Online   5bac9c93-483a-4901-ae46-f6f7ae0a12a8
Central Administration           Online   0c24457f-b58e-4daa-895e-4acd35ef7543
Microsoft SharePoint Foundati... Online   155570fa-0d4c-495d-9f31-5250e83bdd75
Microsoft SharePoint Foundati... Disabled c25ae170-c07d-48db-97b3-73b0d9b47e94
SharePoint Foundation Help Se... Online   8af8b8b1-92cb-48d2-8864-20a7e191d7c2

You can type multiple commands in a script block, either on separate lines or on the same line separated by a semicolon (;). If only one command is entered in the script block, the semicolon is optional, but it is good practice to include it. You can also use local variables to generate a remote script block as in the following example.
$url = ""
$myscript = "get-spsite $url"
$sb = [scriptblock]::Create($myscript)
Invoke-Command $sess -ScriptBlock $sb

You can use the Windows PowerShell Invoke-Command cmdlet to communicate with many sessions, either on the same server or on different servers, from your desktop. This cmdlet enables you to start multiple administrative tasks at the same time that are then run in parallel. However, if these tasks are long running, you will not get control back until the command on the remote machine finishes. This is known as running the command interactively. To run asynchronously as a background job so that the Windows PowerShell prompt returns immediately and you can enter other commands, append the -AsJob parameter to the Invoke-Command, or alternatively, use the Start-Job cmdlet. Using this technique can reduce the amount of time to complete your administrative tasks, compared to running them sequentially. An example of how this can save you a considerable amount of time is during the upgrade process, when each session runs a database-attach-upgrade, and the time taken to complete all database upgrades is limited only by the resources of your SQL Server.

If you have many short-running tasks to complete on a specific server and don't want to keep typing Invoke-Command, use one of the following approaches.

  • You can enter an interactive session with that server by typing Enter-PSSession $sess. The command prompt will change from PS C:\Users\<userid>, where <userid> is the name of the current user, to [<remoteservername>]: PS C:\Users\<remotecredentials>\Documents, where <remotecredentials> is the userid you used for the CredSSP authentication. The command prompt reminds you that you are now submitting commands to the remote server. To return to interactive mode on your local computer, type Exit-PSSession or exit.

  • Use the Import-PSSession remoting cmdlet, also known as implicit remoting, to bring commands from the remote session into the local Windows PowerShell session. An additional advantage of the Import-PSSession approach is that you can interact with your local file system and talk to SharePoint as if you were logged on locally to the SharePoint server. By default, the Import-PSSession cmdlet imports all commands except commands that have the same name as commands in your current session. You can also import a subset of commands and prefix them with a word you specify, so that it is obvious to you which commands are local and which are remote. In the following example, the word Remote is added as a prefix to all SPSite cmdlets.

    Import-PSSession -session $sess -CommandName *-spsite -Prefix Remote

    M ModuleType Name                      ExportedCommands                          
    ---------- ----                      ----------------                          
    Script     tmp_1833f7bc-b269-4229... {Set-SPSite, Backup-SPSite, Get-SPSite,...

    In this example, you can use all SPSite cmdlets as if they were local commands; for example, by typing Get-RemoteSPSite you can return all site collections that match the given criteria. These imported commands are stored in a temporary module that is deleted at the end of the session. To create a persistent module that you can use in future sessions, use the Export-PSSession cmdlet. The imported commands still run in the remote session from which they were imported and therefore may take longer to run than local commands.

When you have completed all of your tasks, you can delete the persistent connection between your local machine and the remote machine by typing Remove-PSSession $sess.

For more information about Windows PowerShell remoting, see Chapter 4, "Using Sessions, Jobs, and Remoting" in the Windows PowerShell 2.0, Administrator's Pocket Consultant, by William Stanek (Microsoft Press, 2009), and the TechNet Magazine article "A Sneak Peek at Remote Management in Version 2.0" at Also take a look at the blog post "A Few Good WS-MAN (WinRM) Commands" at

To open the SharePoint 2010 Management Shell, click Start, and then select Programs, Microsoft SharePoint 2010 Products, and finally, SharePoint 2010 Management Shell, as shown in Figure 5-2.

Starting Windows PowerShell

Figure 5-2 Accessing the SharePoint 2010 Management Shell

The SharePoint 2010 Management Shell is a custom console; it is not the same console that opens if you open the default Windows PowerShell console, a shortcut to which is usually placed on the taskbar. A review of the properties of the SharePoint 2010 Management Shell shortcut exposes the command that is executed.

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe  -NoExit  " &
   ' C:\Program Files\Common Files\Microsoft Shared\Web Server 
   Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1 ' "

The shortcut points to the file Sharepoint.ps1. This is an example of a Windows PowerShell profile, which is identical to any other Windows PowerShell script file and is used to store frequently used elements that need to be automatically loaded at the start of a Windows PowerShell session. Hence, just like normal scripting files, profiles can contain functions, aliases, and variables, and they can load any Windows PowerShell extensions, snap-ins, or modules you might need. A Windows PowerShell snap-in (PSSnapin) is a .NET program that is compiled into DLL files and contains new cmdlets, functions, and/or providers. Windows PowerShell comes with a number of snap-ins, including Microsoft.PowerShell.Core, Microsoft.PowerShell.Host, and Microsoft.PowerShell.WSMan.Management, as well as modules such as ActiveDirectory, FailoverClusters, and WebAdministration. As other products are installed on your computer, additional extensions will become available.

The main aim of the SharePoint profile file is to load the Windows PowerShell for SharePoint snap-in so you can then use the new cmdlets specific to SharePoint. The SharePoint profile file contains the following code, plus a signature.

$ver = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

This code obtains the version of Windows PowerShell, checks that it is greater than 1, and then if that is true, it sets the threading model so that the first thread will be reused, loads the SharePoint PowerShell snap-in, and then changes directory to the home folder, such as C:\users\<userid>, where userid is the person who is currently logged in. For more information on SharePoint, Windows PowerShell, and threading, see the sidebar titled "Memory Considerations When Using Windows PowerShell" later in this chapter.

The SharePoint PowerShell snap-in is not the only snap-in loaded into the SharePoint 2010 Management Shell. Therefore, not only can you use the SharePoint cmdlets, you also can use other cmdlets from the snap-ins that are loaded. To see all the snap-ins and the order in which they were loaded, type Get-PSSnapin. Your output should look similar to the following example.

Name        : Microsoft.PowerShell.Diagnostics
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains Windows Eventing and
              Performance Counter cmdlets.

Name        : Microsoft.WSMan.Management
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains cmdlets (such as 
              Get-WSManInstance and Set-WSManInstance) that are used by the
              Windows PowerShell host to manage WSMan operations.

Name        : Microsoft.PowerShell.Core
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains cmdlets used to manage
              components of WindowsPowerShell.

Name        : Microsoft.PowerShell.Utility
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains utility Cmdlets used to
              manipulate data.

Name        : Microsoft.PowerShell.Host
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains cmdlets (such as Start-
              Transcript and Stop-Transcript) that are provided for use with the
              Windows PowerShell console host.

Name        : Microsoft.PowerShell.Management
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains management cmdlets used to
              manage Windows components.

Name        : Microsoft.PowerShell.Security
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains cmdlets to manage Windows
              PowerShell security.

Name        : Microsoft.SharePoint.PowerShell
PSVersion   : 1.0
Description : Register all administration Cmdlets for Microsoft SharePoint Server.

If you develop your own scripts that can be called from the command prompt or by double-clicking the file in Windows Explorer, and those scripts contain Windows PowerShell for SharePoint commands, make sure that you include the command to set the threading model and load the Windows PowerShell for SharePoint snap-in in your scripts. When calling a script from within a Windows PowerShell console, you can use the #requires tag at the top of your script.

It is common practice to modify the profile file on the designated administrator machine. The profile could be altered so that it

  • Contains all the snap-ins or modules used by all IT professionals in an organization or department.

  • Tracks all Windows PowerShell commands executed.

  • Changes the prompt to indicate the server name. In an organization with a multitude of servers, it is all too easy to start an administrative task on the wrong server, so anything that can help an administrator identify the server he is working on will be helpful, such as configuring the window title to list the name of the server.

An example of a custom profile could contain the following code.

<# ***********************************************************
 Copyright (c)2010, Contoso, All Rights Reserved
Contoso PowerShell Profile - ContosoProfile.ps1
Author: Peter Connelly
Purpose: This profile sets the PowerShell window size, font and title
and loads the SharePoint snap-in
History: Version 1.0 01/02/2010 First version
# Track all Windows PowerShell commands
$profilename = $MyInvocation.MyCommand.Name
$profilepath = $MyInvocation.MyCommand.Path
$transcriptFile = "C:\Contoso\Logs\Powershell_$profilename.log"
Start-Transcript $transcriptFile -append -force
Write-Output "Starting profile: $profilepath"

# Command from SharePoint Server 2010 profile file - SharePoint.ps1
$ver = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

# Check that this is a command-line interface and not the ISE
if ($ -eq "ConsoleHost")
  $width = 80
  $sizeWindow = new-object System.Management.Automation.Host.Size $width,40
  $sizeBuffer = new-object System.Management.Automation.Host.Size $width,9999
  <# Check to adhere to the following rules:
  The buffer width can't be resized to be narrower than the window's current 
  width plus the window's width can't be resized to be wider than the 
  buffer's current width. #>
  $S = $Host.UI.RawUI
  if ($s.WindowSize.width -gt $width)
        $s.WindowSize = $sizeWindow
        $s.BufferSize = $sizeBuffer
  } else {
        $s.BufferSize = $sizeBuffer
        $s.WindowSize = $sizeWindow
# Set foreground, background color and window title
$s.ForegroundColor = "Yellow";$s.BackgroundColor = "DarkBlue";
$s.WindowTitle = "$env:computername"
# #############################################################
# End of ContosoProfile.ps1
# #############################################################

Because the profile script is automatically executed every time you run the SharePoint 2010 Management Shell, it should be signed. More information about customizing your console can be found at

Window PowerShell cmdlets are utilities that are built on top of application interfaces, and in the case of SharePoint 2010, the SharePoint Object Module, and SharePoint Web Services, that allow administrators to complete a number of tasks.

In general, cmdlets use a verb-noun pair. The noun specifies the object you want information about or that you want to manipulate, and the verb states what you want to do with that object. The verbs and nouns are always separated by a hyphen with no spaces, and SharePoint cmdlet verbs have a prefix of SP. For example, if you want to get (the verb) information about all the content databases (noun) in your farm, you would use the following SharePoint cmdlet, which would give you the output shown.

PS C:\Users\Peter> Get-SPContentDatabase

Id               : a1d5c96c-a41a-43b3-bc5d-3f8a93b26046
Name             : WSS_Content_a2fde53006e04bf5aae434ffd3c8a19c
WebApplication   : SPWebApplication Name=SharePoint - 80
Server           : SQL
CurrentSiteCount : 1

Id               : 363b11a3-6947-42f6-9df4-665eeff59c83
Name             : SPF_TeamsDB
WebApplication   : SPWebApplication Name=SPF_Teams
Server           : SQL
CurrentSiteCount : 1

Windows PowerShell also provides a few cmdlets that help you to work with the other cmdlets. Two examples of these are Get-Command, which can be shorted to gcm, and Get-Help, which can be shorted to help. (Shortened names of cmdlets are called aliases.) Get-Command allows you to find cmdlets, and then Get-Help can provide you with basic information about a cmdlet after it is retrieved. (You'll see how to use the Get-Help cmdlet in the section titled "Getting Help" later in this chapter.) In the following example, the Get-Command finds all the cmdlets associated with SharePoint.

PS C:\Users\Peter>Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" |
>>sort noun, verb |Format-Wide -Column 3
When you type a one-line Windows PowerShell script, or you have not provided all the required parameters, Windows PowerShell either prompts you for the parameter or starts a new line with >> so that you can enter more commands. When you have finished typing, press Enter for Windows PowerShell to execute the code. Because of page size restrictions, many of the commands in this chapter are shown on multiple lines when they could be typed on one line, so always remember to press Enter only to execute the scripts.

The set of commands shown previously takes the output from the Get-Command cmdlet and pipes it to the sort cmdlet. The sort cmdlet sorts the data in noun-then-verb order so that all SharePoint cmdlets that manipulate the same object are listed together. The cmdlets that manipulate the same object are then sorted in verb order. To reduce the amount of scrolling necessary in the SharePoint 2010 Management Shell, the sorted data is piped to the format-wide cmdlet. Such a combination of Windows PowerShell cmdlets is quite common. The output from the command set would look similar to the following sample.

Start-SPAdminJob           Get-SPAlternateURL         New-SPAlternateURL
Remove-SPAlternateURL      Set-SPAlternateURL         Install-SPApplicationC...
Start-SPAssignment         Stop-SPAssignment          Get-SPAuthenticationPr...
New-SPAuthenticationPro... Get-SPBackupHistory        Move-SPBlobStorageLoca...
Get-SPBrowserCustomerEx... Set-SPBrowserCustomerEx... Copy-SPBusinessDataCat...
.....(not all output shown)
Set-SPWebApplicationHtt... Get-SPWebPartPack          Install-SPWebPartPack
Uninstall-SPWebPartPack    Get-SPWebTemplate          Install-SPWebTemplate
Set-SPWebTemplate          Uninstall-SPWebTemplate    Get-SPWorkflowConfig

There is another cmdlet similar to the Get-Command that helps you work with cmdlets and that you might find useful—especially if you create your own commands or scripts. It is the Measure-Command cmdlet. This command allows you to measure the time it takes to run cmdlets or scripts. You may also find the Trace-Command cmdlet useful for debugging short script blocks.

There are a considerable number of objects available in SharePoint, and as you might expect, there are more available in SharePoint Server than in SharePoint Foundation. By reading this book, you might have determined the relationship between these objects. For example, while a SharePoint farm can contain many Web applications, each SharePoint farm has one configuration database. Many of the SharePoint cmdlets use names that you can easily identify to determine which objects they will manipulate. To illustrate, the SPFarm cmdlets allow you to retrieve information about and back up or restore a SharePoint farm. For example, the SPFarmConfig cmdlet lets you retrieve and set properties for the farm.

However, there are a few cmdlet names that could confuse you. For example, the SPSite cmdlet allows you to manipulate site collections, and Chapter 2, "Understanding the Architecture of SharePoint 2010," explains that you can't create a site collection unless you have a Web application, which means using the SPWebApplication object. When a site collection is created, you choose a site template to create a site. In the SharePoint Object Model, this site is known as a web and not a site; hence, the object is named SPWeb. This can be quite confusing because the term "website" is often shortened to "site," and in the SharePoint Object Model, "site collection" is also shortened to "site." Because this terminology has been used through many versions of SharePoint and is used consistently by developers, it is easier for IT professionals to adopt this usage.

  • A web is a website and can be manipulated using the SPWeb object.

  • A site collection contains a collection of webs and can be manipulated using the SPSite object.

Figure 5-3 displays the most common objects and their relationships, but there are others, such as SPSiteCollection, which is a collection of SPSites.

The current selection of built-in cmdlets does not provide full coverage of all SharePoint objects, but you can write new cmdlets to manipulate these objects. To determine the objects associated with the SharePoint PowerShell cmdlets and the number of cmdlets per each object, use the commands in the following example, where a portion of the output is shown.

PS C:\Users\peter> Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" |
>>sort noun, verb | group-object -property noun
Count Name                      Group
----- ----                      -----
    1 SPAdminJob                {Start-SPAdminJob}
    4 SPAlternateURL            {Get-SPAlternateURL, New-SPAlternateURL, Rem...
    1 SPApplicationContent      {Install-SPApplicationContent}
    2 SPAssignment              {Start-SPAssignment, Stop-SPAssignment}
...(not all output shown)
    6 SPWeb                     {Export-SPWeb, Get-SPWeb, Import-SPWeb, New-...
    4 SPWebApplication          {Get-SPWebApplication, New-SPWebApplication,...
    1 SPWebApplicationExtension {New-SPWebApplicationExtension}
    2 SPWebApplicationHttpTh... {Disable-SPWebApplicationHttpThrottling, Ena...
    2 SPWebApplicationHttpTh... {Get-SPWebApplicationHttpThrottlingMonitor, ...
    3 SPWebPartPack             {Get-SPWebPartPack, Install-SPWebPartPack, U...
    4 SPWebTemplate             {Get-SPWebTemplate, Install-SPWebTemplate, S...
    2 SPWorkflowConfig          {Get-SPWorkflowConfig, Set-SPWorkflowConfig}

Common SharePoint objects and their relationships

Fig 5-3   Common SharePoint objects and their relationships

Everything that SharePoint knows about an object is stored in data elements and values known as properties, which also describe the state of that object. For example, the SPContentDatabase object contains all the information about the content databases within the farm.

Objects not only have properties, they also contain actions that determine how they can be manipulated. In object-oriented terminology, these actions, or different ways of acting on an object, are called methods. To determine the properties and methods for the SPSite object, use the cmdlets in the following example, where a portion of the output is shown.

PS C:\Users\peter> Get-SPSite | Get-Member

   TypeName: Microsoft.SharePoint.SPSite

Name                                  MemberType Definition
----                                  ---------- ----------
AddWorkItem                           Method     System.Guid AddWorkItem(Sys...
BypassUseRemoteApis                   Method     System.Void BypassUseRemote...
CheckForPermissions                   Method     System.Void CheckForPermiss...
Close                                 Method     System.Void Close()
ConfirmUsage                          Method     bool ConfirmUsage()
Delete                                Method     System.Void Delete(), Syste...
Dispose                               Method     System.Void Dispose()
ToString                              Method     string ToString()
UpdateValidationKey                   Method     System.Void UpdateValidatio...
VisualUpgradeWebs                     Method     System.Void VisualUpgradeWe...
AdministrationSiteType                Property   Microsoft.SharePoint.SPAdmi...
AllowDesigner                         Property   System.Boolean AllowDesigne...
AllowMasterPageEditing                Property   System.Boolean AllowMasterP...
....(not all output shown)
WarningNotificationSent               Property   System.Boolean WarningNotif...
WebApplication                        Property   Microsoft.SharePoint.Admini...
WorkflowManager                       Property   Microsoft.SharePoint.Workfl...
WriteLocked                           Property   System.Boolean WriteLocked ...
Zone                                  Property   Microsoft.SharePoint.Admini...

Never miss an opportunity to pipe the Get-SP<noun> cmdlet to the Get-Member cmdlet. It is sometimes surprising what information an object is able to retrieve.

Real World: Performance Issues When Running Windows PowerShell Commands

If you want to find all the site collections in the farm, you can type Get-SPSite. However, the only output you will see is the URL of the site collections. For performance reasons, the Url property is the only property displayed by default. This is because site collections have many properties; if you display all of these properties for a large number of site collections, you will consume a large amount of memory, and the command will take a long time to run. Displaying just the Url property is almost instantaneous because it is cached. Therefore, you should refrain from running this command to display more than a few additional properties.

To display more than the default property, you can use the select Windows PowerShell cmdlet with the pipe (|) character. You also can use the wildcard character (*) with the select statement to list all the property values, as shown in the following example.

PS C:\Users\Peter> Get-SPSite "http://teams" | select *

ApplicationRightsMask                 : FullMask
ID                                    : cbf3290e-000e-4768-953c-99a983430283
SystemAccount                         : SHAREPOINT\system
Owner                                 : CONTOSO\spadmin
SecondaryContact                      : CONTOSO\peter
GlobalPermMask                        : FullMask
IISAllowsAnonymous                    : False
Protocol                              : http:
HostHeaderIsSiteName                  : False
HostName                              : teams
Port                                  : 80
...(not all output shown)
AllowDesigner                         : True
AllowRevertFromTemplate               : False
AllowMasterPageEditing                : False
ShowURLStructure                      : False

To get a list of all site collections in your farm, together with the name of the content database where they are stored (output that gives only the URL of the site collection and the content database name), you would use the commands as shown in the following example, which also shows the sample output.

PS C:\Users\peter> Get-SPSite | select url, contentdatabase

Url                                     ContentDatabase
---                                     ---------------
http://MySite                           SPContentDatabase Name=Contoso_MySiteDB
http://MySite/personal/peter            SPContentDatabase Name=Contoso_PersonalDB
http://MySite/personal/erin             SPContentDatabase Name=Contoso_PersonalDB
http://intranet.contoso.msft            SPContentDatabase Name=Contoso_IntranetDB
http://teams                            SPContentDatabase Name=Contoso_TeamsDB
http://teams/sites/Finance              SPContentDatabase Name=Contoso_TeamsDB

SharePoint uses common verbs that you have seen with other sets of cmdlets; there are also a number of new verbs added in SharePoint that you may not have seen. Again, you can find these by using the Get-Command cmdlet, as shown here.

PS C:\Users\Peter>Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" |
>>sort verb | group verb | sort count -descending
Count Name                      Group
----- ----                      -----
  139 Get                       {Get-PluggableSecurityTrimmer, Get-SPAccessS...
  104 Set                       {Set-SPAccessServiceApplication, Set-SPAlter...
   88 New                       {New-SPAccessServiceApplication, New-SPAlter...
   77 Remove                    {Remove-PluggableSecurityTrimmer, Remove-SPA...
   11 Update                    {Update-SPFarmEncryptionKey, Update-SPInfoPa...
   10 Add                       {Add-PluggableSecurityTrimmer, Add-SPClaimTy...
   10 Install                   {Install-SPApplicationContent, Install-SPDat...
    8 Start                     {Start-SPAdminJob, Start-SPAssignment, Start...
    8 Import                    {Import-SPBusinessDataCatalogModel, Import-S...
    8 Export                    {Export-SPBusinessDataCatalogModel, Export-S...
    8 Uninstall                 {Uninstall-SPDataConnectionFile, Uninstall-S...
    7 Disable                   {Disable-SPBusinessDataCatalogEntity, Disabl...
    6 Enable                    {Enable-SPBusinessDataCatalogEntity, Enable-...
    6 Clear                     {Clear-SPLogLevel, Clear-SPMetadataWebServic...
    5 Stop                      {Stop-SPAssignment, Stop-SPEnterpriseSearchQ...
    4 Move                      {Move-SPBlobStorageLocation, Move-SPProfileM...
    3 Initialize                {Initialize-SPContentDatabase, Initialize-SP...
    3 Upgrade                   {Upgrade-SPContentDatabase, Upgrade-SPEnterp...
    3 Backup                    {Backup-SPConfigurationDatabase, Backup-SPFa...
    3 Restore                   {Restore-SPEnterpriseSearchServiceApplicatio...
    2 Resume                    {Resume-SPEnterpriseSearchServiceApplication...
    2 Test                      {Test-SPContentDatabase, Test-SPInfoPathForm...
    2 Suspend                   {Suspend-SPEnterpriseSearchServiceApplicatio...
    2 Revoke                    {Revoke-SPBusinessDataCatalogMetadataObject,...
    2 Mount                     {Mount-SPContentDatabase, Mount-SPStateServi...
    2 Grant                     {Grant-SPBusinessDataCatalogMetadataObject, ...
    2 Dismount                  {Dismount-SPContentDatabase, Dismount-SPStat...
    1 Merge                     {Merge-SPLogFile}
    1 Receive                   {Receive-SPSharedServiceApplicationInfo}
    1 Disconnect                {Disconnect-SPConfigurationDatabase}
    1 Unpublish                 {Unpublish-SPServiceApplication}
    1 Connect                   {Connect-SPConfigurationDatabase}
    1 Rename                    {Rename-SPServer}
    1 Restart                   {Restart-SPEnterpriseSearchQueryComponent}
    1 Copy                      {Copy-SPBusinessDataCatalogAclToChildren}
    1 Ping                      {Ping-SPEnterpriseSearchContentService}
    1 Publish                   {Publish-SPServiceApplication}

As you can see, the most common SharePoint-related verbs are

  • Get Queries a specific object or a collection of object and retrieves information concerning that object. For example, you could use it to retrieve information on all service applications. Only Get commands return one or more objects; all other commands execute on one object at a time.


  • Set Modifies specific settings of an object. For example, you could use it to set the site collection owner for a specific site collection.

    Set-SPSite http://teams -OwnerAlias contoso\peter

  • New Creates a new instance of an object, such as creating a new site collection.

    New-SPSite http://teams/sites/HR -OwnerAlias contoso\peter
    -Name "HR Team" -Template STS#0
  • Remove Removes (deletes) an instance of the object, such as a site collection and all its subsites. Because of the dangerous nature of this verb, you usually have to confirm this action by using the -confirm parameter. If this parameter is not present, you will see a message asking you to confirm the action, as shown here.

    PS C:\Users\Peter> Remove-SPSite http://teams/sites/HR
    Are you sure you want to perform this action?
    Performing operation "Remove-SPSite" on Target "http://teams/sites/Finance".
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
    (default is "Y"):y

Parameters are used throughout the examples shown here. These are the words prefixed with a hyphen (-). In the next section, you will look at the Get-Help cmdlet and learn how it can help you find out more about these parameters, including which parameters are available for use with different cmdlets.

Windows PowerShell contains an extensive built-in help system, and you can access it quickly by typing help at the command-line interface. This is an alias for the cmdlet Get-Help. You can even get help about Get-Help by typing Get-Help Get-Help. The output from such a command lists a description of the cmdlet, the syntax used by the cmdlet, parameter descriptions, examples, and other related notes. You also can use the Get-Help cmdlet to get help with the basic Windows PowerShell language. For example, you can use the following commands to get help about specific topics: Get-Help foreach, or Get-Help substring, or Get-Help variables.

The best way to learn Windows PowerShell is to use its built-in help system. If you or your developers create new Windows PowerShell cmdlets, make sure you create your own help files. In addition to the built-in help, there are many resources on the Internet. For example, you can download a free Windows PowerShell Help 2.0 for either 32-bit or 64-bit from

Get-Help finds the information to display by using Extensible Markup Language (XML) files that are installed on the server. When you installed SharePoint, help files were installed along with the Windows PowerShell snap-in. These files can be found in %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\CONFIG\PowerShell\Help or %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\CONFIG\PowerShell\Help\<locale>, where locale defines the language of the computer, such as en-us. These files use the naming convention <dll filename>-help.xml, such as Microsoft.SharePoint.PowerShell.dll-help.xml, Microsoft.SharePont.Search.dll-help.xml, and Microsoft.Office.Access.Server.dll-help.xml. You can find which cmdlets use which XML help file by typing

PS C:\Users\Peter>Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" |
>>sort helpfile, name |
>>Format-Wide name -column 2 -groupby helpfile | more



Get-SPExcelBlockedFileType        Get-SPExcelDataProvider  
Remove-SPExcelDataProvider        Remove-SPExcelUserDefinedFunction

   HelpFile: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions

Get-SPAccessServiceApplication    New-SPAccessServiceApplication 

   HelpFile: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions

Get-SPExcelDataConnectionLibrary   Get-SPExcelFileLocation
Get-SPExcelServiceApplication      Get-SPExcelUserDefinedFunction
New-SPExcelBlockedFileType         New-SPExcelDataConnectionLibrary
New-SPExcelDataProvider            New-SPExcelFileLocation
New-SPExcelServiceApplication      New-SPExcelUserDefinedFunction
Remove-SPExcelBlockedFileType      Remove-SPExcelDataConnectionL...
Remove-SPExcelFileLocation         Set-SPExcelDataConnectionLibrary
Set-SPExcelDataProvider            Set-SPExcelServiceApplication  
-- More -

You can find more information about the format of the cmdlet XML help files and how to make your own help files to complement new cmdlets you create at and

In addition to the command-line help function, there is a graphical help file (WindowsPowerShellHelp.chm) located at %SystemRoot%\Help\mui\<LCID> where LCID is the locale identifier or language of your installation, such as 0409. You can access the graphical help file when using the ISE by selecting the command you want help for and then pressing F1. The chm file opens, and help is displayed for the command, as shown in Figure 5-4.

However, the chm file contains help only for the core Windows PowerShell cmdlets. If you need SharePoint-specific help, you should use the SharePoint 2010 Management Shell and the Get-Help cmdlet.

For more information on the Help feature in Windows PowerShell and how you can configure it to show help for aliases or how to disable local help and force ISE to get help directly from TechNet, see Microsoft recommends that you always check the online help to find the latest information and examples. The link to the online version can be found in the Related Links section when you use the Get-Help command.
Windows PowerShell Help

Figure 5-4 Windows PowerShell graphical help

To find which parameters you can use with a cmdlet, type either Get-Help <cmdlet> or Get-Command <cmdlet> -syntax, where <cmdlet> is the name of the cmdlet you want parameter information about. For example, Get-Help New-SPSite or Get-Command New-SPSite -syntax will provide you with information about the parameters associated with New-SPSite. The Get-Help cmdlet also has several parameters associated with it, and depending on the amount of information you want, you can use them with the Get-Help command. If you know a cmdlet very well and do not want a descriptive explanation of what the cmdlet does, then you may simply want to see some examples of how to use the cmdlet, in which case you would type Get-Help New-SPSite -examples.

To learn about which parameters to use with a cmdlet, review the syntax section of the help results, as shown in the following output. Optional parameters are enclosed within square brackets ([ ]) and the values to be passed to the parameters are enclosed within angled brackets (<>). The following example shows the syntax section of the Get-SPSite cmdlet.

    Get-SPSite [-AssignmentCollection <SPAssignmentCollection>] 
    [-Confirm [<SwitchParameter>]] [-Filter <ScriptBlock>] [-Limit <String>]
    [-WebApplication <SPWebApplicationPipeBind>] [-WhatIf [<SwitchParameter>]]

    Get-SPSite -Identity <SPSitePipeBind> [-AssignmentCollection
    <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-Filter <ScriptBlock>]
    [-Limit <String>] [-Regex <SwitchParameter>] [-WhatIf [<SwitchParameter>]]

    Get-SPSite -ContentDatabase <SPContentDatabasePipeBind> [-AssignmentCollection
    <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-Filter <ScriptBlock>]
    [-Limit <String>] [-WhatIf [<SwitchParameter>]] [<CommonParameters>]

    Get-SPSite -SiteSubscription <SPSiteSubscriptionPipeBind> [-AssignmentCollection
    <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-Filter <ScriptBlock>]
    [-Limit <String>] [-WhatIf [<SwitchParameter>]] [<CommonParameters>]

Notice that there are four ways to use Get-SPSite, and each syntax has an -AssignmentCollection parameter. The -AssignmentCollection parameter relates to an important aspect of the built-in SharePoint cmdlet, which is examined in more detail in the sidebar titled "Memory Considerations When Using Windows PowerShell," which appears later in this chapter.

The first syntax example shown in the listing above has no mandatory parameter, so the Get-SPSite cmdlet would have a scope of the farm or Web application. The other three syntaxes have a mandatory parameter that defines the scope as site collection, content database, or collection of site collections that subscribe to shared settings, features, and services, as shown in the following code. As is the case with the other SPSite cmdlets, in a large installation, this cmdlet could output a large amount of information, and the queries to many content databases could severely affect the performance of the SharePoint servers. Therefore, by default, the output reports only on the first 20 objects.

You can alter this output limit by using the -limit parameter, as shown in the following example, which outputs all site collections that are stored in the Contoso_TeamsDB content database.

Get-SPSite -ContentDatabase Contoso_TeamsDB -limit all

You can provide the values for these scope parameters, or in the case of the -identity parameter, where the value is a URL, you can use the wildcard character (*). The default help with no parameter provides a limited description of the command.

For more information, use the -detailed or the -full parameter. The -full parameter provides additional information about the parameters. For example, additional information about the -identity parameter is shown on the following page.

    -Identity <SPSitePipeBind>
        Specifies the URL or GUID of the site collection to get.

        The type must be a valid URL, in the form http://server_name or http://
        server_name/sites/sitename, or a valid GUID (for example, 12345678-90ab

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?       True
        Accept wildcard characters?  false

If you look at the last five lines of the output, you see that it provides more information on how to use the -identity parameter. For example, the required value is equal to True, which indicates that the -identity parameter is a mandatory parameter for the Get-SPSite cmdlet. However, the position value is equal to 1, which means that if you place a URL of a site collection immediate after the Get-SPSite cmdlet, you do not have to use the -identity parameter because the URL will be read as the identity (URL) of a site collection, where all the property values for site collections that exist under the personal managed path are displayed, as shown in the following example.

Get-SPSite http://MySite/personal/* | Select *

Many of the parameters have a value enclosed in angle brackets, with the suffix PipeBind. This indicates that the parameter can accept an object variable of a specific type. For example, [-ContentDatabase <SPContentDatabasePipeBind>] means that the -ContentDatabase parameter can accept a SharePoint content database object, and this object can be passed to the ContentDatabase object either as a variable, or it can be piped in from the results of another cmdlet. When you pipe an object into a cmdlet, you do not need to type or use a variable. When you pipe an object from one cmdlet into another cmdlet, you do not have to specify the parameter, because Windows PowerShell checks the type of object and will match it to the correct parameter. The following example lists all site collections that are stored in any content databases that have the characters oso anywhere in their names.

Get-SPContentDatabase | where {$ -match "oso"} | Get-SPSite -Limit 50

Get-SPContentDatabase returns a collection of content databases, and then you need to check each content database to see if it matches our condition. The Where-object cmdlet, which has the aliases where or ?, acts like a loop, so it will check each content database object returned from the Get-SPContentDatabase cmdlet. The variable $_ represents one content database object, and .name is the content database property that needs to be matched for our query. The operator is -match.

Windows PowerShell has a number of operators, such as -eq (equal to), -ne (not equal to), -lt (less than), -ge (greater than or equal to), -like (matches a wildcard pattern), and -notlike (does not match a wildcard pattern). The -like, -notlike, -match, and -notmatch operators are used for pattern matching. The -match and -notmatch operators use regular expressions to determine whether a value does or does not contain a match for an expression.

For more information on Windows PowerShell operators, see the section titled "Working with Expressions and Operators" in Chapter 5, "Navigating Core Windows PowerShell Structures," in Windows PowerShell 2.0, Administrator's Pocket Consultant, by William Stanek (Microsoft Press, 2009).

An alternative method to use instead of a WHERE statement is the -filter parameter, which uses the same syntax as the WHERE statement and can produce the same results. However, the -filter parameter executes on the server. Piping the results of the Get-SPContentDatabase cmdlet to the WHERE statement causes a SQL round trip to wherever the Windows PowerShell client is running. Using the -filter parameter can result in a faster performance, allowing the command to leverage the filtering abilities of SQL instead of attempting a local search. However, when you use the -filter parameter, only the Owner, SecondaryOwner, and LockState properties can be accessed for SPSite cmdlets. A number of cmdlets have other parameters that allow you to filter the resulting output. For example, SPWeb provides parameters to filter output on the template or title of the site (web). Still, in many cases the -filter parameter can save you time—for example, finding all the blog sites in a farm of 4300 webs takes about 1.2 seconds with the -filter parameter, but it takes approximately 15 minutes if you use a WHERE statement. Following are several examples that use the -filter parameter.

  • This example returns all site collections whose primary owner has the username peter.

    Get-SPSite -Filter {$_.Owner -eq "contoso\peter"}

  • This example returns all websites in the http://teams/sites/HR site collection that were created using the Blank Meeting Workspace template.

    Get-SPSite http://teams/sites/HR | Get-SPWeb -Filter {$_.Template -eq "STS#03"}

When you create a new site collection, if you do not specify a template or the template cannot be found, then you will need to create a website as the root of the site collection. You can do this by using the New-SPWeb command or by selecting the appropriate site template when you display the site collection for the first time in the browser.

To find details of the templates installed, together with the appropriate template ids, use the Get-SPWebTemplate cmdlet. A sample of the output of this command is shown here.

Name                 Title                                    LocaleId   Custom
----                 -----                                    --------   ------
GLOBAL#0             Global template                          1033       False
STS#0                Team Site                                1033       False
STS#1                Blank Site                               1033       False
STS#2                Document Workspace                       1033       False
MPS#0                Basic Meeting Workspace                  1033       False
MPS#1                Blank Meeting Workspace                  1033       False
MPS#2                Decision Meeting Workspace               1033       False
MPS#3                Social Meeting Workspace                 1033       False
MPS#4                Multipage Meeting Workspace              1033       False
CENTRALADMIN#0       Central Admin Site                       1033       False
WIKI#0               Wiki Site                                1033       False
BLOG#0               Blog                                     1033       False
SGS#0                Group Work Site                          1033       False
TENANTADMIN#0        Tenant Admin Site                        1033       False
ACCSRV#0             Access Services Site                     1033       False
ACCSRV#1             Assets Web Database                      1033       False
ACCSRV#3             Charitable Contributions Web Database    1033       False

On the Get-SPSite and Get-SPSiteAdministration, provide two other filters that use the SQL-driven filtering: the "Wildcard URLs" and regular expression (-RegEx) parameter, for example:

  • Get-SPSite http://intranet/sites/*

  • Get-SPSite "http://intranet/(sites|teams)/HR" -RegEx

Memory Considerations When Using Windows PowerShell

The default behavior of Windows PowerShell is that it runs a multithread environment and that each line, function, or script runs in its own thread ($host.Runspace.ThreadOptions == "Default"). This can cause memory leaks, but as you saw in the section titled "Working with the SharePoint 2010 Management Shell" earlier in this chapter, the SharePoint 2010 Management Shell runs each line, function, or script in the first thread ($host.Runspace.ThreadOptions ="ReuseThread"), which mitigates the problem—but memory leaks can still occur. Hence, the two SharePoint cmdlets that you should learn to use are the Start-SPAssignment and the Stop-SPAssignment. These relate to the -SPAssignmentCollection parameter that you may see used with a number of SharePoint cmdlets to return a "disposable object." In developer-speak, these are objects that implement the IDisposable Interface. If these objects are not disposed of correctly, they can cause memory leaks. In particular, this relates to the SPSite, SPWeb, and SPSiteAdministration objects. If you use cmdlets associated with these objects in one pipe and don't use variables to store the objects, the memory used is automatically disposed of at the end of a pipe. If you have a long pipe that obtains many objects, this can cause a shortage of memory on your SharePoint server, which then can have a noticeable effect on requests for pages from that server.

When you store any of the three objects in a variable, you then have to dispose of the memory assigned to that object. The following examples show the main methods of using these objects with variables and how to dispose of the memory.

  • Use the simple method of using the SPAssignment cmdlets, in which all objects are kept in a global memory store that is released when the Stop-SPAssignment cmdlet is called.

    Start-SPAssignment -Global
    $sc = Get-SPSite http://intranet
    Stop-SPAssignment -Global
  • Use the advanced method of using the SPAssignment cmdlet and tell it to track memory assigned to a specific variable. In the following example, the Start-SPAssignment cmdlet creates a named store that is pointed to by $o, and the variable $sc is associated with that named store and populated with information about the Internet site collection object. The Stop-SPAssignment cmdlet then releases the memory associated with the named store.

    $o = Start-SPAssignment
    $sc = $o | Get-SPSite http://intranet
    Get-SPSite -Limit all
    $o | Stop-SPAssignment
  • If you are used to developing on the SharePoint platform, then you can use a similar technique to that which you use in your code to overcome this issue. For example, use variables within one Windows PowerShell line and dispose of them at the end of that line.

    $sc = New-SPSite("http://Intranet"); $sc.Title; $sc.Dispose()

    This stores the site collection object in the variable $sc. The next command then prints out the title of the intranet site collection, and the last command releases the memory that stored the site collection object.

    This same command can be run safely using the following syntax.
    New-SPSite(http://intranet) | Select Title

Be aware that the simple method of calling SPAssignment shown here also can cause memory problems. Any object you obtain between the Stop and Stop SPAssignment commands will be retained in the global assignment store and will not be released until the Stop-SPAssignment cmdlet is executed, whereas when you use the advanced method of calling SPAssignment, only the memory associated with variables you ask SPAssignment to track will be retained until the Stop-SPAssignment cmdlet is executed. Therefore, if you need to view large amount of information as you complete a task, and you do not want to starve the SharePoint server of memory, the advanced method of using SPAssigment is preferable. Use Get-Help About_SPAssignment to find more information.

SharePoint Foundation 2010 contains over 240 SharePoint-related cmdlets. The exact number can be found by typing the following command.

@(Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell").count

The most common objects that these cmdlets manipulate are the SPSite, SPServer, SPWeb, SPBusinessDataCatalogue, and SPConfigurationDatabase objects. Because Windows PowerShell is mainly an administrator's tool, and these are the components an administrator manages, this spread of cmdlet is not unexpected. These cmdlets also can be found in SharePoint 2010, which is built on top of SharePoint Foundation.

The document "Microsoft SharePoint Foundation 2010 Cmdlet Reference" is included on this book's companion media. This document contains the output that you would see if you typed the following command in the SharePoint 2010 Management Shell.
PS C:\Users\Peter>Get-Command -PSSnapin Microsoft.SharePoint.PowerShell | 
>>Sort Noun, Verb | Get-Help -detailed > CmdletHelp.txt

This command generates a list of cmdlet Help topics that is sorted by noun. This list contains the same Help for each cmdlet that you can view in the SharePoint 2010 Management Shell by typing the following command.

Get-Help <Cmdlet-Name> -detailed

The document contains help information that was current at the time that the document was produced. Microsoft recommends that you always check the online help to find the latest information and examples. You can find the link to the online version in the Related Links section when you use the Get-Help command.

If you use the same Windows PowerShell command shown in the previous section to determine the number of cmdlets available in SharePoint 2010, you will find that there are more than 530 SharePoint-related cmdlets associated with SharePoint 2010. Specifically, that is the number of cmdlets associated with a full install of the Enterprise Edition of SharePoint 2010 without FAST Search installed. To identify the additional cmdlets that SharePoint provides, Windows PowerShell can help again. On a computer with both SharePoint Foundation and a version of SharePoint Server installed, type the following command, changing the name of the redirect file name to reflect the SharePoint installation.

PS C:\users\peter>Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" | 
>> Sort noun, verb |group -Property noun -NoElement > cmdlet_sps.txt

Copy the files to the same server and then type the following command.

PS C:\Users\Peter>Compare-Object -ReferenceObject $(Get-Content .\cmdlet_sps.txt) ' 
>>-DifferenceObject $(Get-Content .\cmdlet_spf.txt)

You will see output similar to the following example.

InputObject                                                 SideIndicator
-----------                                                 -------------
    8 SPContentDatabase                                     =>
    3 PluggableSecurityTrimmer                              <=
    3 SPAccessServiceApplica...                             <=
    9 SPContentDatabase                                     <=
    5 SPContentDeploymentJob                                <=
    4 SPContentDeploymentPath                               <=
    4 SPDataConnectionFile                                  <=
    1 SPDataConnectionFileDe...                             <=
    2 SPEnterpriseSearchAdmi...                             <=
    3 SPEnterpriseSearchLang...                             <=
    4 SPEnterpriseSearchMeta...                             <=

Only those objects that do not appear on both installations, and those for which the count of the number of cmdlets per object is different, will appear in this list. The SideIndicator column indicates from which file the object with its cmdlet count came.

In SharePoint 2010, the most common objects that are manipulated by cmdlets are similar to those in SharePoint Foundation. However, the main additional commands available in SharePoint 2010 are the 131 cmdlets that help you manage the search process. (There are only four cmdlets associated with searches for SharePoint Foundation). Type the following command to check this for yourself.

PS C:\Users\Peter>@(gcm -PSSnapin "Microsoft.SharePoint.PowerShell" | 
>>where {$ -like "*search*"}).count

SharePoint 2010 contains more application services than SharePoint Foundation, such as Excel Services, InfoPath Services, Secure Storage, State Service, Microsoft Visio, and PerformancePoint. Therefore, on a SharePoint Server farm, there are more cmdlets that you can use to create, manipulate, and delete application service objects.

There are two types of administrative tasks that are needed in a SharePoint installation: tasks that need to be completed once and from any server, such as creating a new Web application, configuring the primary owner of a site collection, or deleting a specific website; and tasks that need to be completed more than once on a specific server or on more than one server, such as starting a service on a server, adding or removing a server from the farm, or connecting the server to a specific configuration database. The majority of work you will need to complete as a SharePoint administrator is of the first type—it does not matter which server you are logged on to, because you can complete your work from any server.

Windows PowerShell makes it easier to complete both types of administrative tasks. You can loop around a large number of objects and incorporate the scripts into automated tasks so that administrative tasks can be completed in less time. Just because administrative tasks may be easy to complete using Windows PowerShell, however, you should not allow its use to circumvent the controls you may have in place. Some of these farm-wide tasks are very dangerous; they can affect the whole installation. In a production environment, such tasks should be under strict change management.

Many organizations allow administrative tasks to be completed only by using remote access to the production servers. Computer room access is strictly controlled, so interactive access at the server console is rarely allowed—usually only for hardware-related issues. In such environments, even remote access to the production servers is restricted to a small number of Administrative computers, which administrators have to connect to using a VPN or Remote Desktop. An Administrative computer should be configured to allow only certain users or IP addresses to instigate remote desktop sessions. If this is your scenario, remotely managing your SharePoint Installation using Windows PowerShell should also be restricted to that Administrative computer. Windows PowerShell has a number of built-in capabilities that can help you reduce the risk of tasks that affect the whole of a SharePoint installation; these were referred to in the section titled "Managing Systems Remotely with WinRM" earlier in this chapter.

Windows PowerShell provides a number of "voluntary" capabilities that could be classified as best practices. In the next sections, you will learn more about two of these, the -whatif parameter and transcripts.

Windows PowerShell is a powerful tool, and like any other scripting language, it is all too easy to borrow someone else's code or download snippets from the Internet. You might then execute them without knowing exactly what they do. Using signed scripts and the Windows PowerShell execution policy, as well as restricting who is allowed to load script files onto your SharePoint server, are ways that you can protect your resources.

Windows PowerShell provides a mechanism that allows you to try a command before you execute it—the -whatif parameter. Type the following command.

PS C:\Users\Peter> Get-SPSite http://teams/sites/* | Remove-SPSite -whatif

This command produces the following sample output that lists all site collections and the operation(s) that would be performed on these objects if you executed the command without the -whatif parameter.

What if: Performing operation "Remove-SPSite" on Target "http://teams/sites/Sales".
What if: Performing operation "Remove-SPSite" on Target "http://teams/sites/Blogs".
What if: Performing operation "Remove-SPSite" on Target "http://teams/sites/Finance".
What if: Performing operation "Remove-SPSite" on Target "http://teams/sites/Wikis".
What if: Performing operation "Remove-SPSite" on Target "http://teams/sites/HR".

Nothing has been deleted by trying the command with the -whatif parameter. The parameter tells the Remove-SPSite cmdlet to display the object that would be affected by the command without performing the command. In this example, it displays the objects that would be permanently deleted.

A pair of Windows PowerShell cmdlets, Start-Transcripts and Stop-Transcripts, allows you to record all the commands that you type at the prompt, together with the output. All activity is recorded between the start and stop commands. If you do not type stop, the transcript is terminated when the console session is terminated. This could be very useful in your production environment, where the machine-wide profile contains the Start-Transcript cmdlet to record the Windows PowerShell activities of all users. The recording to the transcript file is complete when they exit the console.

Don't use a Windows PowerShell cmdlet or script for the first time in a production environment. Also, try to keep it simple—don't use or create aliases if scripts are going to be supported by administrators who are new to Windows PowerShell, and always use Windows PowerShell comments when you create or amend scripts.

Real World: What If You Don't Use the –whatif Parameter?

Sometimes even experienced IT professionals can use the built-in cmdlets incorrectly with serious consequences, especially when cmdlets are used in combination with the pipe character. For example, if you type Get-SPSite | Remove-SPSite, all site collections in your farm will be permanently deleted. Everything—all the data in your lists and libraries, and all the content in your websites—would simply be gone. One likely result of this action is that all your help desk telephone lines would immediately ring. If one of the websites that disappeared was your main e-commerce Internet website, your company could quickly lose a great deal of money, and perhaps more importantly, the company could lose potential customers who might never return. To restore your farm, you would need your latest good backup tapes. The lesson of this example is simple: always use the –whatif parameter first!

Many administrative tasks must be completed on a daily basis, some are needed only occasionally, and then there are those few that are rarely required. Windows PowerShell can help with all of these types of tasks; in fact, you may discover that it is more critical to script a rarely executed task than one you perform every day. This may be because you need to execute that rare task quickly and correctly, because the ramifications of making even a small mistake while completing the task could be catastrophic. Throughout this book, you will see many examples of when and how to use Windows PowerShell. In the following sections, you explore a few examples that you may not have seen elsewhere.

There is a section of the Microsoft Script Center,, that contains SharePoint-related scripts.

During the lifetime of your SharePoint installation, there may be many tasks that you must complete (hopefully) only once, such as installing SharePoint and creating your farm. In large organizations with a variety of environments and many developers to support, however, you may find it prudent to develop scripts right from the outset that will build your SharePoint Web front-end (WFE) servers and your SharePoint applications servers, which host your applications services, such as InfoPath Services and search query and indexing services. In previous versions of SharePoint, you could complete such tasks using batch files and the SharePoint command-line tools psconfig and stsadm. You can still use these tools to automate the installation of your SharePoint 2010 and SharePoint Foundation 2010 servers. You will find more information about using these tools in Chapter 4, "Installing SharePoint 2010," so the details aren't repeated here. Microsoft has developed a script that is really the best practice for creating a SharePoint farm from scratch using Windows PowerShell. The order of these commands and parameters can be quite tricky, so Microsoft recommends that you use the Windows PowerShell module, SPModule, documented in the Microsoft's TechNet library article, Install SharePoint Server 2010 by using Windows PowerShell.

For information about SharePoint automation and the use of psconfig, stsadm, and Windows PowerShell, see

When you work on a SharePoint installation, you will need to merge the logs. The Windows operating systems provide you with event logs to help you with your administrative tasks, and you can use the Windows PowerShell Get-Eventlog cmdlet to obtain detailed information from those logs. SharePoint also provides the Unified Logging Service (ULS). The ULS contains all application log events, and third-party logging software can be integrated into them as well. SharePoint 2010 includes several Windows PowerShell cmdlets for retrieving information and configuring the ULS. To find how ULS is configured on your farm, type the following command. (The sample output for this command is also shown here.)


AllowLegacyTraceProviders                   : False
CustomerExperienceImprovementProgramEnabled : True
ErrorReportingEnabled                       : True
ErrorReportingAutomaticUploadEnabled        : True
DownloadErrorReportingUpdatesEnabled        : True
DaysToKeepLogs                              : 14
LogMaxDiskSpaceUsageEnabled                 : True
LogDiskSpaceUsageGB                         : 3
LogLocation                                 : %CommonProgramFiles%\Microsoft Sh
                                             ared\Web Server Extensions\14\LOG
LogCutInterval                              : 30
EventLogFloodProtectionEnabled              : True
EventLogFloodProtectionThreshold            : 5
EventLogFloodProtectionTriggerPeriod        : 2
EventLogFloodProtectionQuietPeriod          : 2
EventLogFloodProtectionNotifyInterval       : 5
ScriptErrorReportingEnabled                 : True
ScriptErrorReportingRequireAuth             : True
ScriptErrorReportingDelay                   : 60
 AllowLegacyTraceProviders                   : FalseCustomerExperienceImprovementProgramEnabled : TrueErrorReportingEnabled                       : TrueErrorReportingAutomaticUploadEnabled        : TrueDownloadErrorReportingUpdatesEnabled        : TrueDaysToKeepLogs                              : 14LogMaxDiskSpaceUsageEnabled                 : TrueLogDiskSpaceUsageGB                         : 3LogLocation                                 : %CommonProgramFiles%\Microsoft Sh                                             ared\Web Server Extensions\14\LOG                                             S\LogCutInterval                              : 30EventLogFloodProtectionEnabled              : TrueEventLogFloodProtectionThreshold            : 5EventLogFloodProtectionTriggerPeriod        : 2EventLogFloodProtectionQuietPeriod          : 2EventLogFloodProtectionNotifyInterval       : 5ScriptErrorReportingEnabled                 : TrueScriptErrorReportingRequireAuth             : TrueScriptErrorReportingDelay                   : 60

When diagnosing a problem, you can use cmdlets associated with the SPLogEvent object. You need machine administrator privileges to run these cmdlets, so you may need to start SharePoint 2010 Management Shell using Run As Administrator. Then you would use commands in steps similar to those shown in the following example.

  1. Set up two variables to store the start day and the end date, for example.

    $SDate = Get-Date -Day 13 -Month 04 -Year 2010
    $EDate = Get-Date -Day 14 -Month 04 -Year 2010

    Or the date could be today's date, but the event occurred approximately 15 minutes earlier than the current time. In this case, you set the variable to 20 minutes before the current time and 10 minutes before the current time.

    $SDate = (Get-Date).AddMinutes(-20)
    $EDate = (Get-Date).AddMinutes(-10)
  2. Obtain a list of events between those two dates and times.

    Get-SPLogEvent -StartDate $SDate -EndTime $Edate

    If the -EndTime parameter is not provided, the event logs will be displayed up until the current date and time.

A tracking number, known as the Correlation ID, is associated with each request you make to SharePoint. This number is stored as a value in a property associated with the SPLogEvent object. SQL Profiler traces also show the Correlation IDs. This number is displayed on an Error page, as shown in Figure 5-5.

SharePoint Foundation error message

Figure 5-5 Error page showing the Correlation ID

In a large or heavily used SharePoint installation, many logs may be produced during the period when a problem occurs. You can use the Correlation ID to help troubleshoot errors by reducing the amount of log information that is returned to those entries that are associated with the incident. Again, set the $sdate and the $edate variables to reflect the time around the incident. For an incident that you can't reproduce and one of your users always can reproduce, you might tell the help desk to ask the user to take a screenshot of the error page so you can be sure to obtain the exact Correlation ID number. Then you can pipe the results of the command shown in step 2 to the Where-Object cmdlet, as shown in the following example.

PS C:\Users\Peter>Get-SPLogEvent -StartDate $SDate -EndTime $EDate |
  where {$_.Correlation -eq "68bc5cf4-5a8c-4517-a879-86e35e57c862"}

The output will display only event logs between the two dates that are related to the problem associated with that Correlation ID.

After you have run the SharePoint 2010 Products Configuration Wizard to install SharePoint on your servers, you can use the SharePoint 2010 Central Administration website to launch the Farm Configuration Wizard. Although it will get you up and running very quickly, it might not configure your farm as you want; for example, the database names it creates will be in the format name_GUID, where GUID is a randomly generated, globally unique identifier. Also, the farm wizard uses the account entered as the Application Pool Identity for the default content Web application and starts the Web Analytics Service by default—both of which may not be desirable on a production farm.

Using the wizard may be sufficient if you want to create a quick prototype or perhaps if you are using SharePoint in a developer environment. However, if any of those environments are limited in their CPU power or in the amount of memory they have, the farm wizard may not be suitable either. For example, the Web Analytics Service uses a large amount of CPU, so your developers might be interested in stopping that service. There are other services that they might want to start and stop on a regular basis, especially if they are using their computers as their day-to-day desktop connections, where they read e-mails and complete documentations, as well as to run SharePoint for development or prototyping.

You can use tools such as the Central Administration website to manage the configuration; however, you may forget to execute all the tasks necessary to complete a configuration change. Instead, you can use Windows PowerShell scripts, which—after you have tested them to make sure that you have not forgotten any tasks—should make managing configuration changes more reliable and error free. You should store these scripts in a central location after they are developed, to make them convenient for fellow administrators to use and incorporate in their environments. Your developer may also thank you for developing these scripts. Such automated tasks might include the following items.

  • To quickly delete a specific Web application, type

    Get-SPWebApplication http://teams | Remove-SPWebApplication –Confirm

  • To remove the Web application, the IIS website, and all the associated databases, type

    Remove-SPWebApplication http://teams –Confirm –DeleteIISSite ' -RemoveContentDatabases

If you do not run the Farm Configuration Wizard, you might find that you need a service that you originally thought you would not need. For example, if no application services are started, and then you try to use one of the SharePoint 2010 workflows, the Microsoft Visio diagram of the workflow progress will not be displayed. However, to solve this problem, you must do more than just create the Visio Application Service. There are other dependencies involved, one of which is the State Service Application. The state services can only be created in the Central Administration site, by using the farm wizard—something you will want to avoid as an administrator. To create the state service using Windows PowerShell, type the following commands.

PS: C:\Users\Peter>New-SPStateServiceDatabase -Name Contoso_StateService_DB |
>>New-SPStateServiceApplication -Name Contoso_StateService |
>>New-SPStateServiceApplicationProxy -Name Contoso_StateService_Proxy -Default
This command may not work in your environment if the associated service instance is not running. For a more comprehensive script, see "SP+PS 2010: PowerShell to Create a Service Application" at

Each service application is slightly different. For example, not all service applications require a database. Chapter 7 "Scaling Out a SharePoint Farm," contains more information about this. However, each service will require a service application proxy, which connects a Web application to the service application.

The following sections provide information about some Windows PowerShell commands you might find useful during an upgrade. The upgrade process is explained in more detail in Chapter 22, "Upgrading to SharePoint 2010."

After installing SharePoint 2010 and before upgrading, you can use the Test-SPContentDatabase cmdlet to check your SharePoint Server 2007 databases for current or potential issues, such as orphan data, missing site definitions, missing features, or missing assemblies. This cmdlet complements the pre-upgrade checker report mentioned in Chapter 22. Checking for these issues does not disrupt your SharePoint installation, and this cmdlet can also test the status of SharePoint 2010 databases, which can assist you in maintaining the continued health of your environment. The following example shows the command and its sample output.

Test-SPContentDatabase -name W_intranet -WebApplication http://www.contoso.msft

Category        : SiteOrphan
Error           : True
UpgradeBlocking : False
Message         : Database [W_intranet] contains a site (Id = [46ad6d70-9a5c-4d
                  e0-8daa-0f73f2466a6a], Url = [/]) whose id is already associa
                  ted with a different database (Id = [6987d2d8-6291-4ead-9eb0-
                  aefe7097a58e], name = [W_Intranet]) in the site map. Consider
                  deleting one of these sites which have conflicting ids.
Remedy          : The orphaned sites could cause upgrade failures. Try detach a
                  nd reattach the database which contains the orphaned sites. R
                  estart upgrade if necessary.

Category        : SiteOrphan
Error           : True
UpgradeBlocking : False
Message         : Database [W_intranet] contains a site (Id = [46ad6d70-9a5c-4d
                  e0-8daa-0f73f2466a6a], Url = [/]) whose url is already used b
                  y a different site, in database (Id = [6063e77c-991f-4c4b-b3a
                  c-68cb62e66502], name = [w_Internet]), in the same web applic
                  ation. Consider deleting one of the sites which have conflict
                  ing urls.
Remedy          : The orphaned sites could cause upgrade failures. Try detach a
                  nd reattach the database which contains the orphaned sites. R
                  estart upgrade if necessary.

The upgrade process is divided into two components, the content database upgrade and the visual upgrade. By separating these two components, your SharePoint team can decide to upgrade the Microsoft Office SharePoint Server 2007 Web application without users noticing the change, because their sites will maintain the old look and feel. Using the browser, they can preview what their site looks like with the new SharePoint 2010 look and feel and then decide when they permanently want to switch to the visual upgrade. After they make the switch, the browser will not allow them to switch back to the SharePoint Server 2007 look and feel.

The Set-SPWeb cmdlet does not have any parameter to help with this task; you will need to use the properties of the SPWeb object to complete this task. Type the following commands if you want to switch sites back to the old look and feel.

Start-SPAssignment -Global
$web = Get-SPWeb http://teams ;
$web.UIVersion = 3;
$web.UIVersionConfigurationEnabled = $true;
Previously in this chapter, you created variables to store values and objects. Variable names are prefixed with the dollar sign, $. In the sample code shown here, you will see $true used. This, together with a number of other keywords that look like variables, is an example of a special variable. A special variable should be treated as a reserved word that you cannot use in your scripts to store values or object. The special variable $true represents the value True, $false represents False, $null represents null, and $_ also has been used in this chapter and contains the current pipeline object. It is used in script blocks, filters, and the Where cmdlet.

After you run these commands, the website will revert to the SharePoint Server 2007 look and feel. The Site Actions button will be in the upper-right corner, for example, instead of in the upper-left corner. The Site Actions menu will have the Visual Upgrade option available, although the Visual Upgrade option at the site collection level may not be enabled. To enable the Visual Upgrade option at the site collection level, use the following commands.

$site = Get-SPSite http://teams
$site.UIVersionConfigurationEnabled = $true

When updating the properties of the SPSite object, there is no update method; the changes to the SPSite properties take effect immediately. You could type the following line as an alternative to the previous two lines of commands.

(Get-SPSite http://teams).UIVersionConfigurationEnabled = $false

To reset all "team" websites within a site collection back to the SharePoint Server 2007 look and feel, use the following command.

PS C:\Users\zzspfarm> Get-SPsite http://teams |
>> Get-SPWeb -Filter {$_.Template -eq "STS#0}|
>> ForEach-Object {
>> $_.UIVersion =3;
>> $_.UIVersionConfigurationEnabled = $false;
>> $_.Update();
>> }
These commands also can be run on a site or site collection that has not been upgraded—that is, on a site that was created as a version 4 site, thereby making a SharePoint 2010 site look like a SharePoint 2007 site.

This chapter explains how you can become familiar with the new Windows PowerShell cmdlets introduced by SharePoint 2010. It explores the SharePoint 2010 Management Shell and how to accomplish some simple but powerful administrative tasks using one-line Windows PowerShell commands.

There are more than 500 SharePoint cmdlets. This chapter could not possibly explain each command; instead, its aim was to provide some general guidelines and good practices for using SharePoint PowerShell in a production environment, such as the configuration and use of remote management, the voluntary use of transcripts, and the use of the –whatif parameter. You should not practice or try out Windows PowerShell commands for the first time on your production environment. Keep your scripts simple, use comments to document your scripts, and don't use or create aliases if the scripts are going to be supported by administrators who are unfamiliar with Windows PowerShell.

The chapter covered two important cmdlets, Start-SPAssignment and Stop-SPAssignment, in some detail. These cmdlets help with cmdlets that return disposable objects, such as SPSite, SPWeb, and SPSiteAdministration. Other SharePoint cmdlets were introduced to expand your knowledge of Windows PowerShell techniques. Chapter 12 builds on this chapter, using search scenarios. The next chapter continues the discussion of SharePoint 2010 farm management and specifically the Central Administration interface.