Using Windows PowerShell to Perform and Automate Farm Administrative Tasks in Microsoft SharePoint 2010

  • 9/3/2010
This chapter 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.
  • Using Windows PowerShell: The Basics

  • Working with the SharePoint 2010 Management Shell

  • Examples of SharePoint Administrative Tasks

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.

Using Windows PowerShell: 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.

This section covers the following Windows PowerShell topics.

  • What’s new in the Windows PowerShell 2.0 release

  • Architecture

  • Installing Windows PowerShell

  • Remote management

What’s New in Windows PowerShell 2.0

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.

Windows PowerShell Architecture

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.

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.

Installing Windows PowerShell

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.

Installing Windows PowerShell 2.0 and WinRM 2.0

A copy of Windows PowerShell 2.0, together with WinRM 2.0, can be downloaded from http://support.microsoft.com/default.aspx/kb/968929. 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.

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.

      Figure 5-1

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

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

    4. On the Installation Results screen, click Close.

Working Within Your Execution Policy

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.

Get-ExecutionPolicy

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.

HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

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.

Managing Systems Remotely with WinRM

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.

Configuring for WinRM

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.

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.

Service
    RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)
    MaxConcurrentOperations = 4294967295
    MaxConcurrentOperationsPerUser = 15
    EnumerationTimeoutms = 60000
    MaxConnections = 25
    MaxPacketRetrievalTimeSeconds = 120
    AllowUnencrypted = false
    Auth
        Basic = false
        Kerberos = true
        Negotiate = true
        Certificate = false
        CredSSP = false
        CbtHardeningLevel = Relaxed
    DefaultPorts
        HTTP = 5985
        HTTPS = 5986
    IPv4Filter = *
    IPv6Filter = *
    EnableCompatibilityHttpListener = false
    EnableCompatibilityHttpsListener = false
    CertificateThumbprint

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.

Meeting Requirements for SharePoint PowerShell Remoting

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
    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

Using WinRM Remoting

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;}

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 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
    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.