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

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

Examples of SharePoint Administrative Tasks

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.

Deploying SharePoint 2010 with Windows PowerShell 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”, at http://technet.microsoft.com/en-us/library/cc262839.aspx.

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

Get-SPDiagnosticConfig
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
                                             SLogCutInterval                              : 30
EventLogFloodProtectionEnabled              : True
EventLogFloodProtectionThreshold            : 5
EventLogFloodProtectionTriggerPeriod        : 2
EventLogFloodProtectionQuietPeriod          : 2
EventLogFloodProtectionNotifyInterval       : 5
ScriptErrorReportingEnabled                 : True
ScriptErrorReportingRequireAuth             : True
ScriptErrorReportingDelay                   : 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.

Figure 5-5

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.

Managing SharePoint Services

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

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.

Using Windows PowerShell During the Upgrade Process

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

Preparing for an Upgrade

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.

Performing Post-Upgrade Tasks

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;
$web.Update();
Stop-SPAssignment

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();
>> }
>><ENTER>