Chapter 2. Introducing Windows PowerShell and SharePoint 2013 cmdlets

In this chapter, you will learn about:

Since the release of Microsoft SharePoint 2010, administrators have needed some form of knowledge about Windows PowerShell. With SharePoint 2013, knowledge of Windows PowerShell has become more of a requirement since Windows PowerShell is replacing the deprecated, but still supported, Stsadm.exe command-line utility. As such, it is critical for SharePoint administrators to have strong Windows PowerShell skills. It is well documented that the SharePoint Central Administration web user interface does not allow for full configuration, administration, and management of the SharePoint environment.

It is important to set the proper expectations for this chapter. Although this chapter will introduce essential Windows PowerShell knowledge for SharePoint administrators, it is not intended to provide complete knowledge of Windows PowerShell, the SharePoint 2013 PowerShell cmdlets, and all the possible combination of scripts or uses; to do so would require an entire book, if not more. Instead, this chapter concentrates on giving you the ability to discover and learn the best ways to create powerful management scripting tools, as well as evaluate the numerous online Windows PowerShell snippets available publicly. To refer to the cliché, the purpose of this chapter is to teach you to fish, or, rather be self-sufficient, rather than simply handing you the fish or reviewing every single cmdlet available in Windows PowerShell and the SharePoint 2013 PowerShell library.

It is also important to note that as of January 2010, all Microsoft server products comply with the Microsoft Common Engineering Criteria (CEC), which requires Windows PowerShell support. Therefore, all of the core technologies and the majority of systems that will integrate with SharePoint will also support, if not rely on, Windows PowerShell scripting to configure, manage, and administer their systems as well.

Windows PowerShell is critically important to SharePoint administration, but knowledge of Windows PowerShell fundamentals is a critical skillset for any Microsoft IT professional or any individual using Microsoft products and technologies.

Exploring the role of Windows PowerShell

Windows PowerShell is a task automation tool created by Microsoft to allow users, typically server administrators, to automate and perform tasks on their on-premises SharePoint environment server(s) or while working with SharePoint Online environments. In this section, you will be introduced to a quick history of the tool and then explore the basic syntax.

Brief history of Windows PowerShell

Windows PowerShell 1.0 was first released in conjunction with Windows Server 2008. At the time, it was described as a new task-based command-line shell and scripting language designed especially for system administration. Windows PowerShell is built on the Microsoft .NET Framework and is meant to assist IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows. Windows PowerShell has built-in commands, called cmdlets (pronounced “command-lets”), which let Windows PowerShell users manage the computers from the command line.

Windows PowerShell 2.0 was released in conjunction with Windows Server 2008 R2 and Windows 7. However, a downloadable install, known as the Windows Management Framework, was also made available for previous versions of the Windows server and client operating systems. The Windows Management Framework not only included Windows PowerShell 2.0, but also the Windows Remote Management (WinRM) 2.0 and Background Intelligent Transfer Server (BITS) 4.0. Arguably, the single most important improvement in Windows PowerShell 2.0 was the introduction of the feature to allow remoting—the ability to run commands on one or more remote computers from a single computer running Windows PowerShell. Windows PowerShell remoting allows for multiple ways of connecting, including interactive (1:1), fan-out (1:many), and fan-in [many:1 by using an Internet Information System (IIS) hosting model]. Additionally, Windows PowerShell 2.0 introduced the Windows PowerShell Integrated Scripting Environment (ISE). The Windows PowerShell ISE is a host application for Windows PowerShell, allowing users to run commands and write, test, and debug scripts in a single Windows-based graphical user interface (GUI) with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.

Finally, Windows PowerShell 3.0 was released in conjunction and as part of the Windows Server 2012 and Windows 8 operating systems. Again, however, a downloadable version of the Windows Management Framework 3.0 includes Windows PowerShell 3.0. Windows Management Framework 3.0 and is available only for Windows Server 2008 R2 with Service Pack 1 (SP1) and/or Windows 7 with Service Pack 1 (SP1). Additionally, the .NET Framework 4.0+ is a prerequisite requirement install on both Windows Server 2008 R2 SP1 and Windows 7 SP1.

When SharePoint Server 2013 is installed, applicable Windows PowerShell cmdlets are available via the SharePoint 2013 Management Shell. Basically, the SharePoint 2013 Management Shell is simply a Windows PowerShell shell that registers the SharePoint 2013 PowerShell extensions (Microsoft.SharePoint.PowerShell.dll) for use within the shell. Most, if not all, aspects of SharePoint 2013 can be managed via Windows PowerShell and the SharePoint extensions.

Basic Windows PowerShell syntax

To reduce the complexity of Windows PowerShell scripting and syntax, all Windows PowerShell scripts revolve around cmdlets. A cmdlet is a single-feature command consisting of a verb and noun separated by a dash (-) that manipulates objects in Windows PowerShell. Examples include Get-Help, Get-Process, and Start-Service (Verb-Noun). This is very different than other command-line interfaces (CLIs) or shells where commands are comprised of executable programs ranging from basic to complex.

In Windows PowerShell, most cmdlets are simple and designed to be used in combination with other cmdlets. For example, the get cmdlets only retrieve data, the cmdlets only establish or change data, the format cmdlets only format data, and the out cmdlets only direct the output to a specified destination.

Additionally, PowerShell cmdlets have a help file that you can access by typing:

PS C:> Get-Help <cmdlet-name> -Detailed

The detailed view of the cmdlet help file includes a description of the cmdlet, the command syntax, descriptions of the parameters, and example(s) that demonstrate use of the cmdlet. However, specific sections of the cmdlet help file can be accessed via specific parameters such as -Examples.

In essence, the most important fact to remember in Windows PowerShell syntax is the verb-noun format with required and/or optional parameters.

Understanding the benefits of Windows PowerShell

GUIs, including the SharePoint Central Administration web application and site, typically use common, basic concepts understood by most computer users. A CLI such as Windows PowerShell uses a different approach to expose information. As it is completely text based from the user’s perspective, it is important to know command names before using them. However, it is possible to compose complex commands that are equivalent to the features in a GUI environment. It is important to become familiar with commonly used commands and command parameters. Unfortunately, most CLIs do not have patterns that can help the user to learn the interface. Because CLIs were the first operating system shells, many command names and parameter names were not selected using common language or syntax.

Windows PowerShell is designed to improve the command-line and scripting environments by eliminating longstanding challenges and adding new, modern features, including:

  • Discoverability. Windows PowerShell makes it easy to discover commands and syntax, as well as features.

    For example, to find a list of cmdlets that view and change Windows services, simply type:

    Get-command *-service

    After discovering the cmdlet that accomplishes a task, it is possible to learn more about the specific cmdlet by using the Get-Help cmdlet. For example, to display help about the Get-Service cmdlet, type:

    Get-Help Get-Service

    To fully understand the output of the specific cmdlet, pass (also known as “pipe,” based on the character being used) the output object to the Get-Member cmdlet to see all the members of the returned Get-Service output “object.” For example, the following command displays information about the members of the object output by the Get-Service cmdlet:

    Get-Service | Get-Member
  • Consistency. The consistency of Windows PowerShell is one of its primary assets. For example, knowing how to use the Sort-Object cmdlet for one scenario enables the user to know how to use it for other scenarios. It is not necessary to learn different sorting routines for different cmdlets or systems. Additionally, new cmdlet developers can rely on existing cmdlets rather than creating new cmdlets for the same functionality. Windows PowerShell encourages developers to use the framework that provides basic features, as well as be consistent about the usage of the interface.

  • Interactive and scripting environments. Windows PowerShell is a combined interactive and scripting environment that grants access to command-line tools and COM objects, and also enables access to the power of the .NET Framework Class Library (FCL). This environment improves upon the Windows command prompt (Cmd.exe), which provides an interactive environment with multiple command-line tools. It also improves upon Windows Script Host (WSH) scripts, which let you use multiple command-line tools and COM automation objects but do not provide an interactive environment.

  • Object orientation. Although Windows PowerShell is text-based from an interaction perspective, Windows PowerShell is based on objects, not text. The output of a command is an object. It is then possible to send (or “pipe”) the output object of one command to another command as its input. Therefore, Windows PowerShell provides a familiar interface for people with other shell experience, while introducing new object-oriented command-line functionality. In other words, it extends the concept of sending data between commands by enabling a user to send objects, rather than simply text as used in STSADM. This also increases the speed in which cmdlets will execute when compared to its STSADM counterparts.

  • Easy transition to scriptingWindows PowerShell makes it easy to transition from typing commands interactively to creating and running scripts. It is possible to enter commands at the Windows PowerShell command prompt to discover the commands that perform a task. Once those commands are known and/or tested, save those commands in a transcript or a history before copying them to a file for use as a script. This offers several advantages; the first is that it documents a repeatable process. The second is the speed at which the process can be duplicated.

Although it may be tempting to use the SharePoint 2013 Products Configuration Wizard and/or the SharePoint Farm Configuration Wizard, most experienced SharePoint professionals, as well as Microsoft, will recommend against the use of wizards in production SharePoint 2013 environments. Additionally, many SharePoint 2013 administrators prefer to utilize the SharePoint 2013 Central Administration web application for making configuration changes to the farm and/or its servers and services.

Utilizing Windows PowerShell to manage and administer the configuration of a SharePoint 2013 environment has many advantages, including:

  • Change control. It is surprising how many production environments do not maintain a change control log. When configuration changes are done via SharePoint 2013 Central Administration or another graphical interface, creating change control log entries can be extremely difficult and usually incomplete. Short of numerous screenshot captures and/or video files, it can be unclear as to what changes have been made to the environment.

  • Disaster recovery. One of the most beneficial items of utilizing Windows PowerShell for installation and configuration is maintaining the scripts in the event of a catastrophic system disaster. The saved scripts can be used to quickly re-create the environment in a disaster recovery situation.

  • Documentation. Most organizations, although directed, fail to maintain proper documentation on their SharePoint 2013 environments. By using Windows PowerShell, it is easy to add the executed scripts from installation, configuration, and change to maintain the documentation of the environment.

  • Fine-tuning configuration. It should be obvious, but not everything can be done via SharePoint 2013 Central Administration or other GUIs. In fact, only via Windows PowerShell can you potentially access all the possible configurations to ensure maximum efficiency and performance of the SharePoint 2013 environment.

It needs to be pointed out that there are certain cases where Windows PowerShell should and should not be used (the latter very rarely), especially when installing and configuring a SharePoint 2013 environment. The most prominent of these scenarios is when configuring the SharePoint 2013 Search service application. You will see an example of this in the final section of this chapter.

Windows PowerShell 3.0 enhancements

Since you will be working with Windows PowerShell 3.0 in SharePoint 2013, it is important to know about several of the significant features that improve its usability and allow you to better manage environments. With Windows PowerShell 3.0, new core cmdlets have been added to support much of the new functionality of Windows PowerShell 3.0. Since Windows PowerShell 3.0 is built upon .NET Framework 4.0, you can use new classes in Windows PowerShell, including Parallel Computing, Windows Communication Foundation (WCF), and Windows Workflow Foundation (WF).

Module autoloading is a significant enhancement to Windows PowerShell 3.0. When using the Get-Command cmdlet, it searches and retrieves all cmdlets and functions from all modules that are installed on the computer system, even if the module is not imported into the current session. Automatic importing of modules is triggered by using the cmdlet in a command, running Get-Command for a cmdlet without wildcards, or running Get-Help for a cmdlet without wildcards. The automatic loading of modules can be controlled by using the $PSModuleAutoLoadingPreference preference variable. The Windows PowerShell 3.0 console improves the tab completion functionality by completing the names of cmdlets, parameters, parameter values, enumerations, .NET Framework types, COM objects, hidden directories, and more.

Arguably, one of most important new features of Windows PowerShell 3.0 is the ability to schedule Windows PowerShell background jobs and manage them both in Windows PowerShell and Task Scheduler. Essentially, scheduled jobs are a combination of Windows PowerShell background jobs and Task Scheduler tasks. Scheduled jobs run asynchronously in the background, like Windows PowerShell background jobs. But, like Task Scheduler tasks, you can run scheduled jobs on a one-time or recurrent schedule or in response to an action or event. You can also view and manage scheduled jobs in Task Scheduler, enable and disable them as desired, use them as templates, run them, and set conditions for which they start automatically. A perfect example would be performing backups of SharePoint on a scheduled basis.

With Windows PowerShell 3.0, support for an updatable, enhanced online help system has been introduced. You can check for and download updated help files for the cmdlets in your modules. The Update-Help cmdlet automatically checks and identifies the newest help files, downloads them, validates them, and installs them in the correct language-specific directory for the module. The Get-Help cmdlet has been enhanced with a new parameter, -Online, which will open the online version of the help topic in your default web browser.

New to Windows PowerShell 3.0 is the ability to utilize persistent, user-managed disconnected sessions, using a PSSession object. The PSSession object is created by using the New-PSSession cmdlet and are saved on the remote computer. Unlike Windows PowerShell 2.0, the PSSession is no longer dependent on the session in which it is created. It is now possible to disconnect from a session without disrupting the commands running in the session. Therefore, you can close the session and even shut down the computer and later reconnect to the remote session from the same or different computer system. Additional cmdlets and parameters have been introduced to support the use of remote, disconnected sessions. However, both the originating (client) and terminating (server) ends of the connection must be running Windows PowerShell 3.0.

These are just a few of the Windows PowerShell 3.0 enhancements that can significantly increase your ability to manage your SharePoint and Windows systems.

Configuring permissions for Windows PowerShell and SharePoint 2013

Depending on whether your SharePoint 2013 environment is hosted on-premises or through SharePoint Online, the administrator who is executing the various SharePoint cmdlets will need a number of permissions. By default, the account that is used to install SharePoint will have the required rights and will be able to provide other accounts with these permissions if needed. The Add-SPShellAdmin cmdlet can be used to grant permissions for users to run the 2013 cmdlets, but to be able to execute this cmdlet yourself, you must have membership in both the securityadmin fixed server role on the SQL Server instance and the db_owner fixed database role on the databases that are to be updated. Additionally, you will also need to be a member of the Administrators group on the server on which you are running the Windows PowerShell cmdlets. The Add-SPShellAdmin cmdlet will add a user to the SharePoint_Shell_Access role for a specified database. If the role does not exist, it will be created at the time of execution. If no database is provided in the –database parameter, then the default behavior is to apply the settings to the Central Administration configuration database. If you use the -database parameter, the user is added to the role on the farm configuration database, the Central Administration content database, and the specified database. Using the -database parameter is the preferred method because most of the administrative operations require access to the Central Administration content database. In addition to adding the specified user to the SharePoint_Shell_Access role for the specified database, the user is also added to the WSS_Admin_WPG group on all web servers. In SharePoint 2010, the use of Add-SPShellAdmin would also add the user specified by the –UserName parameter to the dbo_owner role of the database; this is no longer the case in SharePoint 2013. Executing the cmdlet on a particular database will add the user to the SharePoint_Shell_Access and SPDataAccess roles. The following example will grant a backup administrator account (spAdmin2) the appropriate database permissions to execute SharePoint cmdlets against the database. It is worth noting that you will need to execute the Add-SPShellAdmin cmdlet for all database to which you want to grant access:

$db = Get-SPContentDatabase Contoso_Content_Main
Add-SPShellAdmin –UserName spAdmin2 –database $db

Additionally, the execution policy will be restricted for Windows PowerShell execution. To enable Windows PowerShell execution, you will need to change the execution policy (see Figure 2-1). Remembering your basic format of Windows PowerShell cmdlets, you will use the verb-noun combination of Set-ExecutionPolicy with the desired parameters. Setting the execution policy can be scoped out to the individual user (as shown in Figure 2-1), or to the server level (as shown in Figure 2-2).

Users have the ability to set permissions for the execution policy for the current user only.
Figure 2-1. Users have the ability to set permissions for the execution policy for the current user only.
Users have the ability to set execution policy at the server level.
Figure 2-2. Users have the ability to set execution policy at the server level.

To run scripts, the minimum required execution policy for SharePoint 2013 is RemoteSigned, although the default policy for Windows PowerShell is Restricted. If the policy is left as Restricted, the SharePoint 2013 Management Shell will change the policy for Windows PowerShell to RemoteSigned. This means that you must select Run As Administrator to start the SharePoint 2013 Management Shell with elevated administrative permissions. This change will apply to all Windows PowerShell sessions.

In regards to SharePoint Online, you must be assigned the global administrator role on the SharePoint Online site on which you are running the Windows PowerShell cmdlets. You will learn more about the SharePoint Online management shell in the next section.

Examining the Windows PowerShell management shells

As a SharePoint professional, you will have a number of tools available to allow you to interact with a particular SharePoint environment. While much of the information in this chapter is directed at executing Windows PowerShell cmdlets in on-premises deployments, SharePoint Online has its own management shell that you should be aware of. The SharePoint Online Management Shell allows the SharePoint professional to manage users, sites, and organizations instead of using the SharePoint Online Administration Center. To set up the SharePoint Online Management Shell environment, you will need to install the Windows Management Framework 3.0 (http://go.microsoft.com/fwlink/p/?LinkID=244693) and the SharePoint Online Management Shell (http://go.microsoft.com/fwlink/p/?LinkId=255251). Once the shell is installed, you will need to execute the Connect-SPOService cmdlet similar to the following example. This will need to be done prior to being able to manage users and site collections:

Connect-SPOService -Url https://contoso-admin.sharepoint.com
    -credential [email protected]

Note

If you forget to execute the Connect-SPOService cmdlet prior to executing other SharePoint Online cmdlets, you will receive an error message stating that no connection is available.

With the install of SharePoint Server 2013 on premises, you will have direct access to the SharePoint 2013 Management Shell. The SharePoint Management Shell is simply a Windows PowerShell shell with the additional execution of a script to add the necessary Windows PowerShell cmdlet library and shell environmental variables to easily access SharePoint cmdlets and commands. The actual startup script’s default location is:

C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions
   15CONFIGPowerShellRegistrationSharePoint.ps1

However, most administrators will prefer to use the more fully functional Windows PowerShell Integrated Scripting Environment (ISE) included with the Windows Server operating system.

Windows PowerShell can be utilized to run many aspects of Windows Server 2012, and out of the box, there are few ways to run your Windows PowerShell cmdlets on the server. As shown in Figure 2-3, users have the ability to use the default command-line-driven Windows PowerShell environment and add the appropriate snap-ins for what they are trying to accomplish. For example, if a user wanted to use Windows PowerShell to execute SharePoint cmdlets, they would need to add the SharePoint snap-in as follows:

PS C:> Add-PSSnapin Microsoft.SharePoint.PowerShell
You can execute cmdlets with out-of-the-box Windows PowerShell.
Figure 2-3. You can execute cmdlets with out-of-the-box Windows PowerShell.

Unfortunately, by default, the Windows PowerShell ISE will not include the SharePoint cmdlets. If you attempt to load the snap-in after it has been loaded, it will throw an error. While the error will not halt the execution, you probably don’t want to see red text flying by every time you execute your scripts. To eliminate the error, it is common that you will see –EA 0 at the end of the module name. This is telling Windows PowerShell to handle the error silently. You can use either of the following shorthand examples to load the SharePoint snap-in:

PS C:> asnp Microsoft.SharePoint.PowerShell –EA 0
PS C:> asnp *sharepoint* -EA 0

However, as seen in Figure 2-1 and Figure 2-2, users can simply open the SharePoint 2013 Management Shell to execute SharePoint-specific cmdlets. The downside to using the shell is that it too is a command-line-driven tool. While there are hundreds of cmdlets, once the snap-in has been loaded, you will be able to select cmdlets by typing the verb and then tabbing (that is, using the Tab key and/or Shift-Tab key combination) through a list of available cmdlets. One improvement over the previous version of Windows PowerShell and SharePoint is that the parameters are now viewable in IntelliSense, making it much easier to be productive with the tool.

With Windows Server 2008 R2, Microsoft introduced the Windows PowerShell ISE. ISE is an environment built for users to have more robust control of their scripts and how the scripts are run. In Windows Server 2008 R2, ISE is a Windows feature that needs to be enabled either manually or by running the following cmdlet:

PS C:> Add-WindowsFeature PowerShell-ISE

With Windows Server 2012, ISE is already up and running by default. Figure 2-4 shows the ISE for Windows PowerShell 3.0 in Windows Server 2012.

Windows PowerShell ISE is available by default in Windows Server 2012.
Figure 2-4. Windows PowerShell ISE is available by default in Windows Server 2012.

Since the SharePoint 2013 cmdlets and environment variables are not available by default when using the Windows PowerShell ISE, you can either add the SharePoint snap-in or change the profile for either a specific user or for all users. By default, no profiles are present on a fresh install of a server, but they can be modified to preload the SharePoint snap-in.

Selecting a profile to use in Windows PowerShell ISE

Windows PowerShell ISE supports profiles for the current user and all users of Windows PowerShell ISE. It also supports the Windows PowerShell profiles that apply to all hosts. The profile that you use is determined by how you use Windows PowerShell and Windows PowerShell ISE.

If you use only Windows PowerShell ISE to run Windows PowerShell, then save all your items in one of the ISE-specific profiles, such as the CurrentUserCurrentHost profile for Windows PowerShell ISE or the AllUsersCurrentHost profile for Windows PowerShell ISE.

If you use multiple host programs to run Windows PowerShell, save your functions, aliases, variables, and commands in a profile that affects all host programs, such as the CurrentUserAllHosts or the AllUsersAllHosts profile, and save ISE-specific features, like color and font customization, in the CurrentUserCurrentHost profile for Windows PowerShell ISE profile or the AllUsersCurrentHost profile for Windows PowerShell ISE.

Table 2-1 lists profiles that can be created and used in Windows PowerShell ISE. Each profile is saved to its own specific path.

Table 2-1. Profile paths for different profile types for Windows PowerShell

Profile Type

Profile Path

“Current user, Windows PowerShell ISE”

$profile.CurrentUserCurrentHost, or $profile

“All users, Windows PowerShell ISE”

$profile.AllUsersCurrentHost

“Current user, All hosts”

$profile.CurrentUserAllHosts

“All users, All hosts”

$profile.AllUsersAllHosts

For example, assuming that all users use all hosts for Windows PowerShell for the SharePoint server, you would execute the following Windows PowerShell command in the Windows PowerShell ISE. Be aware that the following example applies to the “All users, All hosts” case, as noted in the $profile. AllUsersAllHosts property of the New-Item cmdlet and powerShell_ise.exe command. You would change the property based upon the desired profile type:

if (!(Test-Path $profile.AllUsersAllHosts)) {
    New-Item -Type file -Path $profile.AllUsersAllHosts –Force
}
powershell_ise $profile.AllUsersAllHosts

As shown in Figure 2-5, this will open another tab in ISE called profile.ps1, into which you would enter the following code and save the profile file:

$ver = $host | select version
if ($ver.Version.Major -gt 1) {
    $host.Runspace.ThreadOptions = "ReuseThread"
}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
The process for setting up a default profile in ISE.
Figure 2-5. The process for setting up a default profile in ISE.

Note

The SharePoint 2013 Management Shell and the Windows PowerShell console differ in the use of the ReuseThread option, which defines how the threading model is used. The use of the SharePoint 2013 Management Shell is defined by the line {Host.Runspace. ThreadOptions = “ReuseThread”}, which is in the SharePoint.ps1 file.

Working with Windows PowerShell cmdlets

As noted previously, all Windows PowerShell cmdlets are verb-noun combinations. And, as one of the specifications for Windows PowerShell is for cmdlets to be discoverable, the most essential cmdlets are those that allow you to discover which cmdlets to use and how to use them.

First and foremost would be to find the appropriate cmdlet. The Get-Command cmdlet helps users accomplish this. With the additional optional parameters of -Noun, -Module, -Syntax, or others and the ability to use wildcards, the Get-Command can be extremely powerful in helping to find the right cmdlet. Additionally, if you are using the Windows PowerShell ISE, you can also use the Commands Add-On (see Figure 2-6), which by default is found on the right side of the Windows PowerShell ISE GUI.

The default Commands Add-On for Windows PowerShell ISE.
Figure 2-6. The default Commands Add-On for Windows PowerShell ISE.

Once the desired cmdlet is determined, use the Get-Help cmdlet and/or the Show-Command cmdlet. The Get-Help cmdlet will display the textual help for the cmdlet specified. The Show-Command cmdlet will show a graphical (GUI) window with both specific and common parameters for the command. Figure 2-7 is an example of the Show-Command window for the cmdlet.

The GUI to set the parameter for the Get-Help cmdlet.
Figure 2-7. The GUI to set the parameter for the Get-Help cmdlet.

When using Windows PowerShell, you can keep the cmdlet help references up to date online if you wish. You will be prompted to do this when first using Windows PowerShell, but can always manually force an update using the Update-Help cmdlet in any Windows PowerShell shell.

As shown in Figure 2-8, once you have found the cmdlet that you desire, use the Get-Command -Syntax cmdlet/parameter combination to get just the syntax of the cmdlets.

An example of using the Get-Command together with the –Syntax parameter for Get-Help.
Figure 2-8. An example of using the Get-Command together with the –Syntax parameter for Get-Help.

For more technical information about the cmdlet, use the Get-Help -Detailed parameter. For examples of how to use the cmdlet, use the Get-Help -Examples parameter, as shown in Figure 2-9. And finally, for the full help file, including all the information on syntax, technical information, and examples, use the Get-Help -Full cmdlet/parameter combination.

The output of the Get-Help examples after help has been updated.
Figure 2-9. The output of the Get-Help examples after help has been updated.

Many times, you will see references in the help provided about the PipeBind object parameter (see Figure 2-10). As discussed earlier in the chapter, keep in mind that all Windows PowerShell cmdlets return objects. You can assign that object optionally to a Windows PowerShell variable composed of unique alphanumeric combinations preceded by a $ symbol (for example, $webApp). Additionally, you can “pipe” the output object of one cmdlet to the next cmdlet in an execution line using the pipe (|) symbol.

The Get-Host Help window within Windows PowerShell ISE.
Figure 2-10. The Get-Host Help window within Windows PowerShell ISE.

Pipe binding allows you to pass output objects without creating variables when references to objects are necessary to return the desired object. If you believe that you may need a reference to an object later, you can assign it to a variable and then pipe in the variable. It is possible to pass the output object from the first cmdlet to the second, and then the output object from the second to the third, and so on, keeping in mind the object type for each cmdlet may and will probably be different. The key is to ensure the output object type of the cmdlet is the required input object type for the PipeBind object of the next cmdlet.

Discovering SharePoint-specific Windows PowerShell cmdlets

As discussed previously in the chapter, the Microsoft.SharePoint.PowerShell.dll file provides the library of almost all SharePoint-specific Windows PowerShell cmdlets. When the Add-PSSnapin Microsoft.SharePoint.PowerShell cmdlet is executed—either manually, by opening the SharePoint 2013 Management Shell, or by a profile.ps1 file for the Windows PowerShell ISE, the references for the SharePoint cmdlets defined in the library are added to the shell environment. Using the Get-Command cmdlet with the -Module parameter, you can easily get the entire list of SharePoint-specific Windows PowerShell cmdlets, as shown in Figure 2-11. Additionally, you can use the Windows PowerShell ISE Command Add-On and limit the cmdlets in the window to the Microsoft.SharePoint. PowerShell module, as shown in Figure 2-12.

An example of the output of Get-Command –Module for Microsoft.SharePoint.PowerShell.
Figure 2-11. An example of the output of Get-Command –Module for Microsoft.SharePoint.PowerShell.
An example of how to find all of the SharePoint Windows PowerShell cmdlets through the ISE interface.
Figure 2-12. An example of how to find all of the SharePoint Windows PowerShell cmdlets through the ISE interface.

One of the most interesting tools now available to help with the building of Windows PowerShell scripts is Microsoft TechNet’s Windows PowerShell for SharePoint Command Builder (http://www.microsoft.com/resources/TechNet/en-us/Office/media/WindowsPowerShell/WindowsPower-ShellCommandBuilder.html). This interactive web-based design (see Figure 2-13) allows you to explore Windows PowerShell cmdlets for different SharePoint platforms, including Microsoft SharePoint Foundation 2010, SharePoint Server 2010, SharePoint Online, SharePoint Foundation 2013, SharePoint Server 2013, and Microsoft Office 365. Additionally, there are a few quick steps available for common functions. The design surface allows for the input of values that will provide the parameters for the cmdlets and, finally, copying to the Clipboard to allow quick pasting in the Windows PowerShell shell.

An image of the Windows PowerShell for SharePoint Command Builder on TechNet.
Figure 2-13. An image of the Windows PowerShell for SharePoint Command Builder on TechNet.

Another interesting website contains the TechNet documentation providing the index of Windows PowerShell cmdlets for SharePoint 2013 (http://technet.microsoft.com/en-us/library/ff678226.aspx). The online index provides all of the SharePoint 2013 cmdlets in both verb and noun order, as well as denoting the new cmdlets for SharePoint 2013 and links to the online documentation for each cmdlet, as shown in Figure 2-14. It is important to note that the cmdlets for on-premises and online are different and the SharePoint Online cmdlets are limited in their functionality, as opposed to the ones provided for on-premises.

The webpage from TechNet that has the index of SharePoint 2013 Windows PowerShell cmdlets.
Figure 2-14. The webpage from TechNet that has the index of SharePoint 2013 Windows PowerShell cmdlets.

The last tool that you should be aware of is the Microsoft TechNet Script Center (http://gallery.technet.microsoft.com/scriptcenter) which is not limited to SharePoint Windows PowerShell scripts; rather, it is a community-driven gallery that provides many Windows PowerShell scripts and can be a good place to learn additional scripting techniques. Keep in mind, though, that because anyone can upload scripts to the Script Center, the scripts available should still be examined and tested thoroughly before using.

Working with SharePoint disposable objects

It is important to remember, similar to programming with certain SharePoint objects, the need to dispose—that is, to explicitly call the IDisposable interface Dispose() method on those objects to release the memory allocation back to the system. Failing to do this in programming, or within Windows PowerShell scripts, can lead to memory leaks, which in turn can lead ultimately to system performance issues or even failure. When using Windows PowerShell to work with certain SharePoint objects, most commonly SPSite and SPWeb objects, you should ensure proper disposal of the objects.

This need for disposal arises from the use of any object that contains or references an SPRequest object. The SPRequest object contains a reference to an unmanaged COM object that handles communications with the database server. Any SharePoint or third-party application or Windows PowerShell script that calls upon any object with reference(s) to the SPRequest object should be examined to ensure proper disposal.

Windows PowerShell will automatically dispose of objects used in commands that appear on a single line or as part of a piped command. However, if you create a variable that stores a reference to an SPSite or SPWeb object, you will need to explicitly or manually dispose of the object when you are done working with the variable. Luckily, there are certain tricks, including a couple of important SharePoint cmdlets, to assist you in ensuring proper SharePoint disposable object disposal.

An example of a single line and piping that would not need the object’s Dispose() method called is:

Get-SPWebApplication | Get-SPSite –limit all | ForEach-Object { Write-Host $_.Url }

However, as mentioned previously, when using an assigned variable to represent the SharePoint disposable object, you will need to explicitly call the Dispose() method like so:

$web = Get-SPWeb http://portal.tekfocus.com/it
# Additional PowerShell script working with $web variable
$web.Dispose()

Finally, arguably the easiest method is to simply wrap all SharePoint disposable objects using Windows PowerShell within the combination of a Start-SPAssignment -Global and a Stop-SPAssignment–Global cmdlet pair, as shown here:

Start-SPAssignment –Global
# PowerShell script using SharePoint disposable objects
Stop-SPAssignment –Global

Any objects defined between the Start- and Stop-SPAssignment –Global cmdlets will automatically have their Dispose() methods called.

Putting it all together

So far in this chapter, you have gained an understanding of the importance of Windows PowerShell in a SharePoint environment and how to ensure that you will be able to both use it from a permission standpoint and explore the hundreds of cmdlets that are available. While it only takes a little tinkering to get an intermediate level of understanding of the Windows PowerShell cmdlets for SharePoint, there are additional advanced tasks in SharePoint that benefit from the use of Windows PowerShell. Prior to diving into some advanced scenarios, you will first explore how to build a simple site. From there, you will get an understanding of how to configure one of the more complex service applications: SharePoint Search.

Creating a sample site (site collection)

In this first example, the key takeaway is the use of variables that are prefixed with the dollar sign ($). While you don’t always need to use variables, they do offer some readability to your scripts. Examine the following syntax. The use of SharePoint cmdlets doesn’t happen until the final line, where you see the use of the New-SPSite cmdlet and a number of parameters that follow. The parameters are prefixed with the hyphen (-).

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0
$siteURL = "http://portal"
$owner = "ContosoAdministrator"
$template = "BLANKINTERNET#0"
$name = "Portal"
$description = "This is a sample site that was built using PowerShell."
New-SPSite $siteURL -OwnerAlias $owner -name $name -Template $template -Description $description

SharePoint 2013 Search service application topology management

SharePoint 2013 uses the web-based interface within the SharePoint 2013 Central Administration web application to show the current status of the search topology. The primary way to change the topology is by using Windows PowerShell. This is a significant change from the previous version, as SharePoint Server 2010 also included a web-based option for changing the topology. The reason for this is that the core search architecture of SharePoint 2013 has a more complex and flexible topology that can be changed more efficiently by using Windows PowerShell. Also, keep in mind, the search capabilities of SharePoint Foundation 2013 have changed and are now based on the same search implementation as SharePoint Server 2013. This provides many improvements, but it also means that the search configuration is very different from the SharePoint 2010 Foundation but similar to SharePoint Server 2013 Search.

For specific information on changing the SharePoint Server 2013 Search service application topology, refer to http://technet.microsoft.com/en-us/library/jj862356.aspx, which contains references to Windows PowerShell to modify the SharePoint 2013 Search service application topology.

In this next example, you will see the use of comments. These are notes created by the author and are ignored by the system. These lines begin with the pound sign (#). The script may look a little more daunting than the last, but because of commenting, everything here should make sense to you.

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0
# Define App Pool Name
$saAppPoolName = "SharePoint Web Services Default"
# Search Specifics, we are single server farm
# Define Search Server Name
$searchServerName = "Contoso-SP3"
# Define Search Application Name
$serviceAppName = "Contoso Search Service Application"
# Define Root for Search Database Names
$searchDBName = "Contoso_Search"
# Assign the Appplication Pool for Service Application Endpoint
$saAppPool = Get-SPServiceApplicationPool $saAppPoolName
# Start Search Service Instances
Write-Host "Starting Search Service Instances..."
Start-SPEnterpriseSearchServiceInstance $searchServerName
Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance $searchServerName
# Create the Search Service Application
Write-Host "Creating Search Service Application and Proxy..."
$searchServiceApp = New-SPEnterpriseSearchServiceApplication  -Name $serviceAppName
   -ApplicationPool $saAppPoolName -DatabaseName $searchDBName
# Create the Search Service Proxy

$searchProxy = New-SPEnterpriseSearchServiceApplicationProxy  -Name "$serviceAppName Proxy"
   -SearchApplication $searchServiceApp
# Clone the default Topology (which is empty) and create a new one and then activate it
Write-Host "Configuring Search Component Topology..."
$clone = $searchServiceApp.ActiveTopology.Clone()
# Get the Search Instance Information
$searchServiceInstance = Get-SPEnterpriseSearchServiceInstance | where
   {$_.Server.Address –eq $searchServerName}
# Create the Search Service Administration Component
New-SPEnterpriseSearchAdminComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Create the Search Service Content Processing Component
New-SPEnterpriseSearchContentProcessingComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Create the Search Service Analytics Processing Component
New-SPEnterpriseSearchAnalyticsProcessingComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Create the Search Service Crawler Component
New-SPEnterpriseSearchCrawlComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Create the Search Service Indexing Component
New-SPEnterpriseSearchIndexComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Create the Search Service Query Component
New-SPEnterpriseSearchQueryProcessingComponent –SearchTopology $clone
   -SearchServiceInstance $searchServiceInstance
# Activate Search
$clone.Activate()
Write-Host "Search Done!"

Note

You can read more about the Search service and its components in the “Search service application” section of Chapter 4.

As you work with Windows PowerShell, you will undoubtedly need a deeper understanding of its capabilities. While this chapter has given you a good foundation, as well as enough insight into Windows PowerShell to be successful, there are still many elements that have been left out. There are many online references and books that can help you gain a deeper understanding of this material.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset