Home > Sample chapters > Programming > Visual Studio and .NET

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

Working with the SharePoint 2010 Management Shell

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.

Figure 5-2

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.

Understanding cmdlets

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

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

Working with Objects

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
>><ENTER>
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}
Figure 5-3

FIGURE 5-3 Common SharePoint objects and their relationships

Understanding Properties and Methods

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

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

Using Verbs

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

    Get-SPServiceApplication
  • 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
    Confirm
    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.

Getting Help

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.

Help Files

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

Get-SPExcelBlockedFileType        Get-SPExcelDataProvider
Remove-SPExcelDataProvider        Remove-SPExcelUserDefinedFunction
Set-SPExcelFileLocation

   HelpFile: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions
\14\CONFIG\PowerShell\Help\microsoft.office.access.server.dll-help.xml
Get-SPAccessServiceApplication    New-SPAccessServiceApplication
Set-SPAccessServiceApplication

   HelpFile: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions
\14\CONFIG\PowerShell\Help\Microsoft.Office.Excel.Server.MossHost.dll-help.xml

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 -

ISE Help

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.

Figure 5-4

FIGURE 5-4 Windows PowerShell graphical help

Using Parameters

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.

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

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

    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.

PARAMETERS
    -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
        -cdef-1234-567890bcdefgh).

        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 {$_.name -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.

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

    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

cmdlets for SharePoint Foundation 2010

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.

cmdlets for SharePoint 2010

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

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

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 {$_.name -like "*search*"}).count
>><ENTER>

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.

Performing Basic Administrative Tasks

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.

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.

Using the –whatif Parameter

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.

Generating Transcripts

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.