Chapter 10: Administering SharePoint 2010 with Windows PowerShell

What’s In This Chapter?

  • Basic Windows PowerShell usage
  • How to use common SharePoint 2010 cmdlets
  • The SharePoint object model

PowerShell is now the command-line tool for administering SharePoint 2010. In previous versions of SharePoint, administrators worked with STSADM.exe. Starting with SharePoint 2007, we began seeing some integration with PowerShell and SharePoint. With no commands provided we managed to create our own PowerShell commands and scripts for SharePoint 2007. To do so some of us had to get our hands dirty and either put on our developer hat or beg, borrow, and steal from friends on the Internet. Ultimately, we ended up with some PowerShell scripts for SharePoint 2007 even if we really didn’t understand how they worked under the covers. With the 2010 version of SharePoint, the use of PowerShell for administration is different, much different.

Now we have commands and a management shell that installs with SharePoint 2010 — and when we say commands, we mean a lot of commands, well over 500. STSADM only boasted around 185 commands. More important, these 500 plus commands can be chained together and scripted, enabling you to create practically an infinite number of scripts and commands.

In this chapter we will get you up to speed on PowerShell in general, and then show you how to harness the power of this beast to benefit your SharePoint 2010 farm.

Introduction to Windows PowerShell

There is no requirement that you must use PowerShell to administer SharePoint 2010. Basically every administrative function is exposed through the SharePoint user interface. Many administrative tasks are easily done via Central Administration or Site Settings. While it is conceivable that a SharePoint 2010 administrator could avoid using PowerShell, what fun would that be? PowerShell really starts to shine when you want to perform repeatable processes or multiple tasks.

For example, you can create site collections using Central Administration — one site collection at a time. But with a little knowledge of PowerShell and the SharePoint commands you can create a comma-separated list of many site collection URLs and supporting information, and then use PowerShell’s Import-CSV cmdlet with the New-SPSite cmdlet to create them with a single click of the Enter key.

note.ai

If you are worried that STSADM is no longer available, rest assured that STSADM is still around, for now. The writing is on the wall, however; PowerShell is now the command-line tool for SharePoint administrators. Microsoft says STSADM is deprecated, which is a fancy way of saying it will be removed in a future version. Start saying goodbye to STSADM.

Microsoft SharePoint 2010 Management Shell and Other Hosts

PowerShell is included in Microsoft Windows Server 2008 and is activated as a feature. However, it is version 1.1, and SharePoint 2010 requires version 2. Because PowerShell version 2 is a prerequisite for SharePoint 2010, the prerequisite installer will try to install it. You’ll get an error if the PowerShell version 1.1 feature is activated. Simply deactivate it and run the prerequisite installer to get the correct version of PowerShell installed. Windows Server 2008 R2 comes with PowerShell version 2 already installed and enabled. You may get an error when the prerequisite installer runs, but you can ignore it. The correct version of PowerShell is installed and patiently waiting for SharePoint to come out and play.

Microsoft SharePoint 2010 Management Shell

The Microsoft SharePoint 2010 Management Shell is displayed in Figure 10-1. This is the default, out-of-the-box SharePoint command-line interface. Not much to look at. As a matter of fact, it looks a lot like the command console you used to run STSADM commands in SharePoint 2007. It is, however, a cleverly disguised PowerShell console, with the PowerShell commands registered and ready for use. Open the SharePoint 2010 Management Shell and PowerShell at the same time. If you squint, you might see that they look pretty similar. The only obvious difference is that the SharePoint Management Shell has a black background, while the standard PowerShell background is blue. They may look similar, but only the Management Shell will run the SharePoint commands without further configuration.

note.ai

You can run STSADM commands inside of PowerShell. Add the path to STSADM to the system’s path variable and call all the STSADM commands you like.

Run a very basic SharePoint command in both consoles — for example, Get-SPSite. The Management Shell will happily return a list of site collections, whereas the PowerShell console won’t have a clue what you want it to do.

In other words, the big secret is that the SharePoint 2010 Management Shell is just the PowerShell.exe with a command-line parameter that points to a PSC1 file or a console file. The PSC1 file tells the PowerShell host to register the SharePoint commands. One other minor difference is that it also has a title bar that says SharePoint 2010 Management Shell, but otherwise the Management Shell is all PowerShell.

Using Other Windows PowerShell Hosts

While the Management Shell is the only host that is configured to run SharePoint commands, it is not the only host that an administrator can use. Administrators can choose to work with other PowerShell hosts. Two common hosts are available with Windows Server 2008 and Windows Server 2008 R2: Windows PowerShell and Windows PowerShell Integrated Scripting Environment, more commonly known as ISE. ISE is displayed in Figure 10-2. Administrators can also use many of the third-party PowerShell hosts available free or for purchase. Many of these boast a rich graphical user interface. The rest of this chapter sticks to the Management Shell because it is the lowest common denominator, but we realize that many of you will want to know how to configure these other hosts to use the SharePoint 2010 PowerShell commands, so we cover that here.

Adding commands is similar for all hosts. We will be adding commands to the PowerShell ISE host. ISE provides a multi-line editor with breakpoints and other help for scripting. You might need to consult the documentation for other third-party hosts.

ISE is installed with Windows Server 2008 and Windows Server 2008 R2 but it is not activated. To activate ISE, use the Add Feature screen of the Server Manager. Figure 10-3 shows the Server Manager’s Add Feature screen with the ISE feature checked.

To register the SharePoint PowerShell commands with ISE you must be working locally on a SharePoint 2010 server. The SharePoint 2010 PowerShell commands do not remote.

note.ai

SharePoint 2010 commands must be run on a SharePoint 2010 server. The commands cannot be run from a client. PowerShell 2 does provide a remoting scenario whereby commands can be executed from a client to run on the server. This is a PowerShell function and not specific to SharePoint 2010. To learn more about configuring Windows PowerShell remoting with SharePoint 2010, read this blog post: http://blogs.msdn.com/opal/archive/2010/03/07/sharepoint-2010-with-windows-powershell-remoting-step-by-step.aspx.

Use the Add-PSSnapin PowerShell command to register the SharePoint PowerShell commands:

Add-PSSnapIn Microsoft.SharePoint.PowerShell

Add-PSSnapIn is a PowerShell command that will register commands. The Microsoft.SharePoint.PowerShell snap-in contains the registration information for the SharePoint commands.

This will get you started. To verify that the SharePoint 2010 commands are available in ISE, simply run a SharePoint command such as Get-SPSite. ISE should respond with a list of site collections on the farm. Note one tiny issue: You are required to add the Microsoft.SharePoint.PowerShell snap-in every time you start the host. To avoid this, you can run the command to add the snap-in to your profile, which will run each time you start a host.

You can locate your profile by typing $Profile into the command line, which will return the path to your profile. $Profile is a variable containing the current user’s profile location. The profile location may be different for each host. The ISE profile is different from the PowerShell profile, so commands for the ISE user’s profile will not interfere with other PowerShell hosts. If the profile exists already, you can use the following command to open your profile:

Notepad $Profile

If the profile exists, Notepad will open it. If the profile does not exist but the directory exists, Notepad will prompt you to create a new file. Add the Add-PSSnapin command with the Microsoft.SharePoint.PowerShell value into your ISE profile and save it. You will need to restart ISE to read in the profile changes. When you need a command, variable, or function to persist between sessions, you can use the profile.

Commands

PowerShell is powered by commands. Commands get things done. There are four basic types of commands: cmdlets, functions, scripts, and native commands. It is not necessarily important to know the differences among these command types to work with PowerShell and SharePoint, but it doesn’t hurt either. If you are just starting out with PowerShell, you can find a wealth of general information at http://microsoft.com/PowerShell.

Cmdlets

Cmdlets (pronounced command-lets) are compiled commands that are registered with PowerShell. They have a very specific naming convention: All cmdlets are named with a verb-noun combination. The verb portion of the name should be one of the PowerShell accepted verbs. PowerShell defines a list of these verbs and what they mean at http://msdn.microsoft.com/en-us/library/ms714428(VS.85).aspx. Because the verbs are “standardized,” you can usually guess the verb portion of the cmdlet. An example of a cmdlet is New-SPWebApplication, which has a corresponding Remove-SPWebApplication. You might have expected to use the verb “delete” to delete a SPWebApplication, but delete is not one of the standardized verbs, so it cannot be used.

Cmdlets are installed and registered. As you might have already guessed, the SharePoint commands that we will be using are cmdlets. You saw that SharePoint installed the cmdlets on the server, and the Management Shell registered them with the host using the PSC1 file; and you now know how to manually register them in the ISE. You can also create custom cmdlets, but that is a topic beyond the scope of this book. You can learn more about writing your own cmdlets in this MSDN article: http://msdn.microsoft.com/en-us/library/dd878294(VS.85).aspx.

Functions

Functions can contain one or more commands to accomplish a task, and can accept parameters that allow the creation of custom reusable code. They are defined in PowerShell by typing the function into the host. PowerShell then compiles the function and verifies the syntax. Functions can be reused for the lifetime of the host session. If you close the host, then you lose the function; and it will need to be entered again when you start another session with the host. You can enter functions into your profile so they will be available whenever you start a session.

warning.ai

There’s nothing worse than working on an award-winning function, only to lose it when you shut down the host. Consider yourself warned and save your function in your profile or at least to a text file so you can copy it later.

Functions have their place and are great for containing code that you will want to call from various other scripts or commands, but with a single chapter for administering SharePoint using PowerShell, we have no space to cover them in depth here.

Scripts

Scripts are a combination of commands, functions, and practically anything PowerShell. Because SharePoint 2007 did not have cmdlets, PowerShell scripts were very important. Now that we have more than enough cmdlets with SharePoint 2010, they are not as important for daily work. Scripts are useful for common reusable code, but SharePoint administration often results in the use of “one-liners.” There is no big secret behind scripts; create a script in your favorite text editor or ISE and save it to the file system with a .PS1 file extension. Later you can run the script by typing in the filename.

Scripts, in contrast to functions or PowerShell snap-ins, survive the host shutdown and can easily be recalled. Another great benefit of the script is that once a script is created and tested, it can be saved to a script library and reused. By default, the hosts do not run unsigned scripts. Hosts will warn if you attempt to run a script that has not been signed. You can modify the security setting using the cmdlet Set-ExecutionPolicy. Because so much can be accomplished using the SharePoint cmdlets, we will not be doing much with scripts in this chapter. Scripts are only necessary if you want to chain together a complicated series of cmdlets, or walk through complicated loops.

warning.ai

For security reasons, the PowerShell application is not associated with .PS1 files. The default application associated with .PS1 files is Notepad, so double-clicking a .PS1 file will open the file in Notepad. This effectively stops the user from double-clicking a malicious script and running it. If you change the file association, which is not recommended, you run the risk of inadvertently running a malicious script.

Native Commands

Native commands are commands that run outside of the host process. We have already used a native command, Notepad. If you are still hooked on STSADM.exe, you can use STSADM as a native command in the host. But with all the PowerShell goodness and the SharePoint commands, why would you?

Basic PowerShell

Entire books have been written on PowerShell, so it is not possible to cover the basics in a single chapter. But we won’t just you throw you to the wolves with PowerShell. Here we cover a few key things to help the newer “PowerShellers” out there (or is it “SharePointShellers”?). Many of the SharePoint PowerShell commands can be used as a one-liner or “standalone,” so a true understanding of PowerShell is not always required. That said, understanding a few PowerShell concepts in conjunction with the SharePoint commands can help you along the way.

Listing the SharePoint Commands

PowerShell provides the Get-Command cmdlet to retrieve a list of available commands. The Get-Command parameter will retrieve all commands that are known to the host. Get-Command, like many commands, accepts optional parameters. Since we are interested in only the SharePoint 2010 commands, we can limit the commands displayed to just the SharePoint 2010 commands by using the optional -Module parameter. To list only SharePoint commands, execute the following command:

Get-Command -Module Microsoft.SharePoint.PowerShell

Figure 10-4 displays the output of the Get-Command cmdlet using the –Module parameter.

Did you catch all that? At last count there were over 500 PowerShell cmdlets included with SharePoint 2010. This might still be a few more commands than you want to list. The list can be pared down some if you use the optional -noun or -verb parameter for Get-Command. For example, if you were wondering what commands work with a Web application, use the following command:

Get-Command –Module Microsoft.SharePoint.PowerShell –noun SPWebApplication

If you need to know which command to use for backups, use the following command:

Get-Command –Module Microsoft.SharePoint.PowerShell –verb Backup

Figure 10-5 shows how you can control the output of Get-Command with the –noun and –verb parameters.

PowerShell Help

As shown in the preceding section, Get-Command will help you determine which command you should use to accomplish a task. Get-Help will help you understand the usage of a command. The Get-Help command is a standard PowerShell cmdlet. To get help for a particular command, simply call Get-Help, passing in the name of the command for which you want help. For example, if you wanted to see help about New-SPWebApplication, you would use the following:

Get-Help New-SPWebApplication

Figure 10-6 shows the help returned for New-SPWebApplication. It provides you with numerous details about the command, including parameters, examples, and usage. Get-Help accepts the optional parameters of -detailed and -examples. Examples of your options are shown at the bottom of Figure 10-6 under the Remarks heading. To learn more about Get-Help, simply use Get-Help Get-Help — a little redundant but it works.

PowerShell Variables

We can’t ignore the topic of variables, which gets us frighteningly close to developer work. In a basic sense, variables hold information. Typically, variables don’t come into play until you start doing more of the common one-liner commands. All PowerShell variables start with the $ character and can hold any type of object.

note.ai

Certain objects in SharePoint such as SPWeb, SPSite, and SPSiteAdministration, must be properly disposed of. One-liner SharePoint commands will dispose of all objects correctly. Storing these SharePoint objects in variables can lead to performance issues and memory leaks if the variable is not handled correctly. This section on variables specifically avoids using these SharePoint objects until the dispose subject can be addressed later in the chapter.

In Figure 10-7, the variable $webApps is set to the output of Get-SPWebApplications. $webApps now contains all of the Web application (SPWebApplication) objects. You use the count property to determine how many Web applications are contained in the variable. You can display the Web applications by simply typing the variable name.

note.ai

Wondering which commands were used to get the output displayed in the screenshots of the Management Shell? Just take a look at the top of the figures to see the commands following the Administrator prompt.

The Formerly Dreaded “Objects”

We thought we would add a few words about our friends, the objects. As administrators, we have been able to stay blissfully ignorant of these pesky little devils. Until now. In previous versions of SharePoint we had STSADM. STSADM was good to us. When we needed to interact with it, we gave it strings like http://portal.company.com, WSS_ContentDB, or domainusername. And when STSADM replied back to us, it reciprocated with easy to understand strings. Strings are just text, so they’re easy to use. We managed SharePoint with strings and we liked it. Then this fancy PowerShell comes along with its snap-ins and its cmdlets and its objects. What exactly is an object? It’s complicated, but it helps to think of an object like a car. Like an object, a car has properties. Properties are information about the object, things like color, numberoftires, make, model, smellslikefeet, and so on. If we’re given the object car, instead of the word “car” we can use those properties to make decisions. If we get a group of car objects, we can decide to only view the blue ones by checking the car.color property. That’s one place where strings let us down. When we got a list of site collections from STSADM we got text. If we wanted information that wasn’t in the text, we had no way to get more information, and if the information we needed was hidden somewhere in that string, we had to do complicated text manipulation to get it out. Objects make sorting this out easier.

Like our objects, cars also have methods. Methods are actions you can do with your object. In our car example a method might be start, accelerate, slowdown, rolldownwindows, driveoffcliff, and so on. Objects are the same way. We have methods associated with different object types. Those methods are one way we interact with the objects. The SPSite object has a dispose method, which flushes it out of RAM. It also has a delete method, which is one way to delete an SPSite object. See, objects aren’t scary at all. Okay, maybe a little.

Hopefully after this little chat we’ve all become fans of objects and we appreciate them for the functionality they provide, and no longer hold their complexity against them.

It’s important to note that the Get-SPWebApplication cmdlet does not include your Central Admin web application by default. You have to include the parameter –IncludeCentralAdministration for Central Administration to be included. Also, if you have only a single content web application the .count does not return 1, like you would expect. It returned nothing, nada, zilch.

Variables enable you to hold onto objects and data for later use in your commands and scripts. Obviously, variables do not survive a host shutdown, but you can create and set a variable in your profile. This book generally avoids using variables because so much can be done to administer SharePoint 2010 without them, which also avoids any disposal issues.

PowerShell Pipeline

The PowerShell pipeline is how you chain commands together. Why chain together commands? Cmdlets are usually good at one specific task such as listing SPSite objects (think site collections). You can chain together many commands to do a more specific or targeted task. The Get-SPSite command will return all site collections in the farm. The Get-SPWeb command will return a specific web object. If you needed to retrieve all SPWeb objects, you could chain the Get-SPSite command to the Get-SPWeb command using the PowerShell pipeline. To get all the SPWeb objects on the farm (excluding any within the Central Administration Web applications), use the following command, as shown in Figure 10-8:

Get-SPSite –Limit ALL | Get-SPWeb –Limit ALL

We cannot leave this discussion of the pipeline without at least mentioning .NET objects. The pipeline passes .NET objects between commands. The word “objects” might scare you a little, but you have been working with objects for some time now — with VBScript, CScript, and WMI, to name a few. Objects simply contain information and methods to act on the information or the environment. While you might shy away from objects, the fact that PowerShell uses .NET objects makes life a lot easier. For example, you can use a function such as Get-SPSite to return SPSite objects and send them to a command that will alter the objects. For a lot of what you do, objects will be sitting in the background.

Controlling Output

Now that you know a little about the pipeline and its use of objects, we need to take a look at how to control the output of these objects. The pipeline uses objects, but all we really work with in the Management Shell is text. No problem; PowerShell is a smart application. When an object hits the end of a pipeline, it must be captured, set to void, or formatted for the screen as text. We have already looked at using variables, so you should be familiar with the concept of capturing. Void is a fancy developer term for nothing, get lost, I don’t want you. We won’t worry much about void. Formatting, however, is something to worry about, because if you don’t take care of formatting, PowerShell will.

In many cases it is not a big deal that we let PowerShell format our objects for display. When an object makes it to the end of the pipeline, the default formatters take effect. Many SharePoint objects have a default format, which is usually a table format with a few key properties. Let’s take a look at the default formatting for the SPFarm object using the Get-SPFarm command.

In Figure 10-9 it appears that there are only two properties associated with the SPFarm object: Name and Status. While those are key properties, they are not the only properties associated with the SPFarm object. The default format for the SPFarm object displays only the Name and Status properties.

So how do you get to look at more properties? When you control the output, you get to decide how you want the objects formatted. You control the format using the format commands, the most common of which are Format-List and Format-Table. There are a few others, but this section looks at only these two common formatting commands.

Format-List will display object properties in list format. Each object gets one or more rows to display a property and a value. When you see text fly across the screen during some of your outputs, you can probably assume that you are looking at objects formatted in list style. At this point, we’ll go ahead and send our SPFarm object to the Format-List command. Figure 10-10 displays the SPFarm object’s properties in List view. The Format-List command also accepts an optional Properties parameter, which enables you to provide a comma-separated list of property names to be displayed.

Format-Table will display an object’s properties in tabular fashion. Each object gets a single row and one or more columns depending on what properties should be displayed. The default format for most objects is table style, so simply piping the objects to the Format-Table might not get you much further. What will help is the optional Property parameter, which accepts a comma-separated list of properties to display. You could choose to display all SPFarm properties using the following command:

Get-SPFarm | Format-Table *

If you do that, however, you will get a result that is practically unreadable because you attempted to put too many columns in such a small amount of space. The Format-List command is better for showing a large number of properties. For example, instead of displaying all properties, you can display only the DisplayName, Status, and BuildVersion properties. Figure 10-11 shows the result of using the following command:

Get-SPFarm |Format-Table –Property DisplayName, Status, BuildVersion

Due to space limitations, this chapter doesn’t cover many other formatting commands and even output commands to pipe content to files, including CSV. To learn more, use these two help commands:

Get-Help Format

Get-Help Out

note.ai

To clear the screen, use CLS, which is an alias for Clear-Host.

Using SharePoint Commands

With more than 500 individual SharePoint 2010commands, one chapter cannot possibly cover them all. This section will get you started working with some of the more common SharePoint commands for PowerShell.

Working with the Farm

The Farm is the top-most SharePoint administrator object, containing key properties and collections associated with the SharePoint farm. The term “farm” can be confusing, especially in a single-sever environment. A farm is one or more servers that share the same configuration database. The association of farm and configuration database is carried through as the farm’s name is the configuration database name.

In SharePoint 2007, we used the Farm object quite often when we scripted commands to get to all the collections and properties. With the many SharePoint 2010 commands, you can now access many of these properties using a more specific command. The farm still contains many key properties and methods that can be used for administration. For example, you can determine the farm’s status, display name, and version.

You can access the farm using the Get-SPFarm command (refer back to Figure 10-9). The output of this command is nothing special. The default formatting for the SPFarm object is to display the Status and DisplayName. However, you learned earlier how to control formatting of the objects, so feel free to modify the output of the SPFarm object.

To access a specific property on the SPFarm object, use dot notation (.). You could also do this using a variable, but this has its own complications, which are covered at the end of this chapter when we cover object disposal. For example, to access the BuildVersion property of the SPFarm object, use the following command:

(Get-SPFarm).BuildVersion

The parentheses tell the command that you want the BuildVersion property of the result of the Get-SPFarm command. The result of the Get-SPFarm command is an SPFarm object. Without the parentheses, PowerShell would interpret your command as “get the BuildVersion property of the Get-SPFarm command,” which does not have a BuildVersion property. Figure 10-12 shows the result.

There are quite a few methods for the SPFarm object, but we won’t cover any of these because SharePoint includes specific commands for many of these methods, such as backup and restore. There’s no point spending time learning how to work with the object model when you can simply call a command.

Besides viewing and accessing properties of the farm, you can also back up and restore the farm using PowerShell and SharePoint commands. The backup command is Backup-SPFarm; and the restore command is Restore-SPFarm. The purpose of these cmdlets is obvious thanks to the nice verb-noun naming convention.

The backup command requires a Backup method and Directory parameter. If you don’t include these parameters, the command will prompt for them. The BackupMethod can be Full or Differential. The directory is the location where you want the files to be placed. Just supply the path, not the filename, for the Directory parameter. There are also optional parameters for the Backup-SPFarm command. Use Get-Help Backup-SPFarm to see these optional parameters. One particularly interesting parameter is the ShowTree parameter. Figure 10-13 displays the Backup-SPFarm command and its output.

Backing up would be useless if we could not restore the data. Restore-SPFarm requires the Restore method and a directory where the backup should be located. The Restore method can be either overwrite or new. Overwrite will overwrite the original location, whereas new will create a new database. Figure 10-14 shows the help for Restore-SPFarm.

Retrieving Farm Configuration Information

We need to touch on the topic of the Get-SPFarmConfig command. This command will return farm-level configuration information for items that are not on the SPFarm object. Figure 10-15 displays the output of the Get-SPFarmConfig command.

You can use the corresponding Set-SPFarmConfig to modify the values. It is a little bit more than a single command. You need to get the FarmConfig into a variable, change the value of the property, and then pipe the modified FarmConfig variable to the Set-SPFarmConfig command. Figure 10-16 shows the output.

The commands in Figure 10-16 modify the farm’s WorkFlowBatchSize property. This property determines how many workflows can be processed at one time by the farm. The default value for this is 100. The lines above change this setting to 105 and writes the value back to the farm.

Working with Web Applications

Every SharePoint site collection is associated with a single Web application. The SPWebApplication object represents a Web application. The Web application contains many properties that an administrator might want to look at, such as those associated with the Recycle Bin, Official File, List throttling, and status. Using the SharePoint commands, you can list all Web applications including the Central Administration Web application, create new Web applications, remove Web applications, and modify Web application properties.

First, let’s see all the Web applications on the farm. The Get-SPWebApplication command will display all the Web applications on the farm except for the Central Administration Web application. That is probably a good thing, as you probably don’t want to treat the Central Administration Web application the same way we treat your content Web applications. To get all Web applications on a farm, including the Central Administration Web application, use the Get-SPWebApplication command with the IncludeCentralAdministration switch parameter, as shown in Figure 10-17.

Getting all the Web applications might not be exactly what you need. Sometimes you need a single Web application. To retrieve a single Web application, you use the Identity parameter. This parameter is smart enough to accept a name, Url, or Id of the Web application. You rarely see the –Identity parameter actually named. Normally, you can omit the name of the parameter, and name only the Url or Id, as shown in Figure 10-18.

The SPWebApplication has a lot of properties and methods. To see the properties of this specific Web application, you can pipe it to Format-List as shown in Figure 10-19.

As Figure 10-19 demonstrates, the web application object has a lot of properties. To be honest, all the SharePoint objects have a lot of properties. How are we supposed to discover all these properties and keep track of them? Fortunately we have a command for that. Get-Member will return the members of the object passed into it via the pipeline. To determine what properties and methods are available on the SPWebApplication object, use the following command (the output is shown in Figure 10-20):

Get-SPWebApplication http://sharepoint | Get-Member

If piping the output through Format-List gives you more information than one screen can handle, you can additionally pipe it through the More command:

Get-SPWebApplication http://sharepoint | Get-Member | More

This will give you one page of output at a time. Press the spacebar to see the next screen. You can also scroll one line at a time by pressing the Enter key.

To access a specific property on the SPWebApplication object, use the dot notation described earlier. To access the Id of the http://sharepoint Web application, use the following command:

(Get-SPWebApplication http://sharepoint).Id

While it is nice to be able to access the Web applications, you might just want to create or remove a Web application. It’s clear why you might want to remove a Web application, but why would you want to create a new one using PowerShell? Creating a new Web application is a great way to repeatedly build out your demo environments. The New-SPWebApplication cmdlet, shown below and in Figure 10-21, creates a new Web application, which contains many parameters — some required and some optional. The following simple example demonstrates how to create a new Web application. To see all the parameters, use Get-Help New-SPWebApplication.

New-SPWebApplication –Name "Portal" –Port 80 –HostHeader portal.contoso.com –Url 

http://portal.contoso.com –ApplicationPool DemoAppPool –ApplicationPoolAccount (Get

-SPManagedAccount contosoSP_serviceapps)

note.ai

When trying the code in Figure 10-21 you may get an error telling you that you need “machine privileges.” This happens if your SharePoint 2010 Management Shell was not started with the Run as Administrator option. Without elevated permissions SharePoint can’t always access what it needs. If you get any errors like this, make sure your management shell window has “Administrator:” at the beginning of the title bar.

You can use the Get-SPWebApplication command to verify that the Web application was created, but astute readers will notice that the newly created SPWebApplication object was formatted for the screen already. You could capture the SPWebApplication in a variable or pass the object onto another command via the pipeline. If you do capture the object in a variable, make sure you read the section “Disposing of SharePoint Variables” at the end of this chapter. Notice that we are calling the Get-SPManagedAccount command to retrieve an SPManagedAccount object, which is required for the AppPool account. You can see what managed accounts you have by using the Get-SPManagedAccount command with no parameter, as shown in Figure 10-22.

Now that you know how to create a web application using the SharePoint commands, it would be useful to learn how to remove an SPWeb application. It probably comes as no surprise that to remove a web application, you use the Remove-SPWebApplication command. This command requires you to select a specific web application, which prevents the deletion of multiple applications at once. Figure 10-23 shows how to remove the web application you just created.

Notice how PowerShell is smart enough to prompt you before it destroys your precious information. Yes, there is a way to “override” this helpful prompt, but we will leave that as an exercise for readers who want to learn enough about PowerShell to change this setting and take responsibility for the consequences. We don’t need any midnight phone calls when you accidentally delete your web application.

Working with Site Collections

The site collection level is where life gets interesting, for a number of reasons. First, since the 2003 version of SharePoint there has been a disconnect between the way the site collections are referred to in the Administration UI and object model. Next, the objects that you will be working with in this section require the proper disposal; otherwise your application might just start to hiccup, or worse.

Let’s start by clarifying that a site collection is represented in the SharePoint object model as an SPSite. That should be enough clarification for the purposes of this section. We have looked at site collections in various chapters of this book already. The site collection belongs to one and only one Web application. The site collection is generally defined as a boundary for items such as content types and permissions. Like other objects in SharePoint 2010, you can list, create, modify, and remove a site collection or SPSite using the SharePoint PowerShell commands. You can also back up and restore a site collection using PowerShell.

note.ai

The SPSiteAdministration commands Get-SPSiteAdministration and Set-SPSiteAdministration allow administrators who do not have access to the site collection to manage certain elements of it. Use of the SPSite-based commands assumes some amount of access to the site collection.

Let’s start by listing all site collections on the farm. There are two common methods to do this. If you do not need to list the Central Administration site collection (see the section “Working with Web Applications”), you can use the Get-SPSite command as described earlier in this chapter. As usual, the default formatting for the SPSite object provides only a few items for display. Figure 10-24 shows the Get-SPSite command in action.

The Get-SPSite command, as well as other Get commands in SharePoint 2010, will return only 20 items before providing a warning that the list was limited. These commands limit the number of objects returned for performance reasons. You will greatly appreciate the limit functionality of the Get commands the first time someone tries to return hundreds of sites and webs. The Get-SPSite command has an optional Limit parameter that can be set to a number or to All if you wish to return all items. You will see how to use the Limit parameter in the following section.

If you want to include site collections associated with Central Administration, you need to start with the Get-SPWebApplication command with the IncludeCentralAdministration parameter. You then need to pipe the results to the Get-SPSite command, as shown in Figure 10-25.

Of course, sometimes you need to get a single site collection or possibly a smaller subset of site collections. Using SharePoint 2010, along with some basic PowerShell commands, you have several ways to do just that.

To get a specific site collection, you can use the Identity parameter. Like the Identity parameter used with the Get-SPWebApplication command, you can provide the command with a few different values; and like the Get-SPWebApplication command, the actual word Identity is generally not seen. In this case, the Identity parameter can use wildcards as well as regular expressions (when used in conjunction with the RegEx switch parameter). To get a single site collection, simply pass in the Url as a parameter to the Get-SPSite command, which is piped to the Format-List command as demonstrated in Figure 10-26. Feel free to throw an asterisk into the mix to see what you get back.

The Get-SPSite command also has an optional Filter parameter that will perform server-site filtering of site collections, which provides a faster way to limit the SPSites returned. The Filter parameter will limit the results of the Get-SPSite command using a script block. A script block is simply a block of script enclosed by brackets. The Filter parameter can be used to filter on Owner, Secondary Owner, and LockState. Figure 10-27 shows the use of the Filter parameter and the script block. The $_ represents the current object in the pipeline.

Don’t forget about using the pipeline to filter your site collections. The Filter parameter will only filter on Owner, Secondary Owner, or LockState. What happens if you need to select on other properties? If you can’t seem to get from here to there using any of the preceding methods, you can always reach for the Where-Object command. The Where-Object command is a PowerShell command that uses a script block to filter objects. You commonly use the $_ reference to the current pipeline object to check a property and decide whether to keep the object or ignore it. Use Get-Help Where-Object to learn more about the Where-Object command. The following example reaches out a little further and retrieves only those site collections that have a single SPWeb object, which is the root web:

Get-SPSite –Limit All |Where-Object {$_.allwebs.Count –eq 1}

Before removing any site collections, let’s look at the backup and restore options. It’s a good practice to back up the site in case you realize you really needed it after removing it.

By now you should be able to guess that the command to back up a site is Backup-SPSite. The site collection backup requires that you identify the site to back up and the path, including the filename, to save the backup image. This command by itself will back up only a single site collection. For example, to back up the site.Contoso.com/teams/IT site collection, you would use the following command:

Backup-SPSite http://site.contoso.com/teams/IT -path c:ackupscontosoitit.bak

While that’s handy, it doesn’t scale very well. Part of the “power” of PowerShell is its ability to loop through objects. Earlier in this chapter you saw how easy it is to get a list of all of your site collections. You also know how to back one up. Therefore, you may be thinking that you should be able to combine those two tasks in order to back up all of your site collections. If so, your instincts are correct. PowerShell provides exactly that capability. Behold, the “back up all of your site collections in a single script” script:

Get-SPWebApplication | Get-SPSite | ForEach-Object{$FilePath = "c:ackups" +

 $_.Url.Replace("http://","").Replace("/","-") + ".bak" ; Backup-SPSite –Identity

 $_.Url -Path $FilePath}

There’s a lot going on there, but when it’s broken down it’s easy to understand. The first two cmdlets get the list of web applications and site collections in the farm. The next part walks through the list of site collections and for each one creates a variable named $FilePath that consists of C:ackups plus the name of the site collection, with the protocol (http://) removed and any slashes in the URL replaced with dashes. Finally, you use your old friend Backup-SPSite to back up the current site collection to the location you just built with $FilePath. So simple, yet so powerful.

You’ve probably already figured out that you would use the Restore-SPSite command to restore the backup. The Restore-SPSite command requires the usual standard Identity and Path parameter. To restore the it.bak file, use the following command:

Restore-SPSite http://site.contoso.com/teams/IT -path c:ackupscontosoitit.bak

Now that you have a backup and know how to restore the site collection, it is time to finally remove the site collection. To do that, you use the Remove-SPSite command. Like other destructive commands, you will be prompted for each site collection you want to delete. Although the Remove-SPSite will remove only one site collection, you are free to pass the SPSite object into the Remove-SPSite command using the PowerShell pipeline. You can now appreciate the fact that PowerShell prompts you to allow the deletion of each and every site collection.

Now is also a good time to talk about PowerShell’s WhatIf parameter. Well-behaved cmdlets that are potentially destructive in nature support the optional WhatIf switch parameter, and the Remove-SPSite cmdlet is indeed one of those cmdlets. If you add the WhatIf switch parameter to the Remove-SPSite command, the command will not actually remove the site but instead indicate what will happen if you remove the WhatIf parameter. Nice touch, isn’t it? It might not make sense if you are working with a single site but imagine if you ran this command:

$WebApps = Get-SPWebApplication -IncludeCentralAdministration

Now you have a variable that contains all Web applications. Suppose you later decide to remove all site collections. That is easy enough: $WebApps | Get-SPSite | Remove-SPSite. That is fine until you realize, too late, that you just deleted the Central Administration site collection. With the WhatIf parameter, you are forewarned about the pain you are about to inflict on yourself. Figure 10-28 shows you how a smart administrator can leave work on time.

Consider using the WhatIf parameter whenever you use a command that might destroy your data. It will help avert those frantic late-night restores and a fair amount of swearing.

Working with Webs

Site collections contain webs or SPWebs if you are speaking about SharePoint PowerShell commands. Like the other main objects in the SharePoint hierarchy, you can list, add, modify, and remove webs. Administrators tend to spend a lot of time working with webs because they are so numerous and this is where end users actually do their work. The SPWeb object contains many items that end users work with, such as lists and libraries. Now is probably a good time to let you know that there are no commands to access objects below the SPWeb object. This means that there are no commands for lists, libraries, or files, to name a few objects below the SPWeb object. However, that does not mean you cannot access them via PowerShell — just that you will not find cmdlets specific to these objects. You are free to access these objects via the object model.

Listing all the webs of the farm is slightly different from listing SPWebApplications or SPSites. The Get-SPWeb cmdlet requires at least one parameter. It will not list all SPWebs on the farm if you omit the parameters. On the plus side, you are allowed wildcards, regular expressions (with the use of the –RegEx switch parameter), and filters (with a script block), similar to Get-SPSite. The Identity parameter will also accept a relative path if the Site parameter is used.

Let’s look at a few ways to list SPWebs starting with a single web. To access a single SPWeb object, use the Identity parameter, passing in the Url as demonstrated in Figure 10-29.

Now use the Filter parameter to filter your SPWebs on the server side, which performs better than returning all SPWebs for further filtering. The Filter parameter can be used with the Template and Title properties of the SPWeb. Remember to use a script block with a Filter parameter. The following command returns a list of SPWebs that are based on the Blank Team site:

Get-SPSite | Get-SPWeb –Filter {$_.Template –eq "STS#1"}

The next example returns all the SPWebs in the farm, including any Central Administration webs, sorted by Url and displaying only the Title and Url:

Get-SPWebApplication –IncludeCentralAdministration | Get-SPSite |Get-SPWeb |

Sort-Object Url | Format-Table Title, Url

Figure 10-30 displays the results of the attempt to display all of the SPWebs on the farm. As discussed earlier, the cmdlet will limit the number of objects returned to 20 for performance reasons. If the number of objects is greater than 20, a warning will be displayed. To display all of the SPWebs, you need to add the Limit property set to All for both Get-SPSite and Get-SPWeb:

Get-SPWebApplication –IncludeCentralAdministration | Get-SPSite –Limit All |

Get-SPWeb –Limit All|Sort-Object Url|Format-List Title, Url

Creating a new web is similar to creating new site collections. You use the New-SPWeb command and a host of parameters to define the new SPWeb. One of these parameters, Urlis required; but the rest are optional, such as Name and Template. The following command creates a new SPWeb based on the Team Site template:

New-SPSWeb –Url http://site.contoso.com/teams/IT/SP2010, 

-Template "STS#1" –Name "SP 2010 Implementation"

Once the web has been created, the SPWeb object is returned and displayed on the screen.

You cannot back up or restore an individual web; that is reserved for the site collection and farm. What you can do is export and import a web. Because we just created a new web, let’s go ahead and export it. To export the web, use the Export-SPWeb command, passing in the Identity and Path parameters. The Path parameter indicates where the exported web file will be placed, and it must include both a filename and the path. Use the Export-SPWeb command to export your new web:

Export-SPWeb http://corpNet.contoso.com/ops -Path c:ExportWebopsExport.cmp

You can import the web into an existing or new web. The Import-Web command requires the identity of the web to import to and the path to the exported web file. The command to import your exported site to a new web is as follows:

Import-SPWeb http://corpNet.contoso.com/DemoImport -Path c:ExportWebopsExport.cmp

Finally, you can remove your web by using the Remove-SPWeb command. This command is similar to the Remove-SPSite command. It removes one web at a time, prompting users for confirmation along the way. You can pipe an unlimited number of SPWebs into the remove command. Don’t forget the earlier discussion of the WhatIf parameter. As shown in Figure 10-31, use the WhatIf parameter to see what would happen if you ran this command:

Get-SPSite |Get-SPWeb –Limit All |Remove-SPWeb –WhatIf

As you can see, the pipeline is very powerful. Be careful when you pipe objects into destructive commands. The WhatIf parameter and PowerShell’s confirm message will help to keep you out of trouble — that is, if you pay attention!

Working with Objects below the Web Level

As mentioned earlier, SharePoint PowerShell commands generally work from the SPWeb object and above. That means you will not find commands such as Get-SPList or New-SPLibrary in the out-of-the-box commands. That does not mean that there is no way to access these and other items not exposed by the included commands. It means that we need to start thinking more like developers and attack the object model. This is exactly how we worked with SharePoint 2007 and PowerShell when we had no SharePoint cmdlets. We had to walk uphill both ways to and from school, and we liked it! This section does not delve too far into this subject, but it looks at how you can use PowerShell to list a web’s lists and libraries, and add and then remove a SharePoint list. That will provide you with the foundation to move outside the commands supplied by SharePoint 2010.

Lists and libraries are children object of the SPWeb object we just looked at. The SPWeb object contains a single property, Lists, which is a collection of all its lists and libraries. To retrieve all the lists and libraries of a specific web, you can use the following command, as shown in Figure 10-32, within the Management Shell or a host with the SharePoint commands registered:

(Get-SPWeb http://sharepoint/team/blog).Lists

It is likely that there is a lot of text flying across your screen now as all the properties of all the lists and libraries are displayed. Unlike the previous SharePoint objects you have worked with, the SPList list object that is returned from the preceding command does not have a defined default format; therefore, PowerShell does its best formatting by dumping all the properties.

note.ai

Control+C will exit the current processing and return you to your prompt.

None of us can read that fast. Fortunately, you can control how each list is formatted and slow down some of that flying text. Run the same command, but this time send the lists and libraries out to Format-Table, which is another PowerShell formatting command, as shown in Figure 10-33.

(Get-SPWeb http://sharepoint/team/blog).lists | Sort-Object Title | Format-Table 

Title, Id, ItemCount, hasUniqueRoleAssignments, EnabledAttachments, EnableThrottling

note.ai

Many of the lower-level objects such as SPList and SPListItem will not save their changes to the content database until the Update method is called on the object.

Now that you know how to retrieve all the lists and libraries contained within a SharePoint web, the following example demonstrates how to get just one specific list. The Lists property on the SPWeb object returns a collection of lists, like many of the properties associated with SharePoint objects. You can retrieve any list by using the index, Id, or title. For example, to get the third item in the lists collection, use the following:

 (Get-SPWeb http://sharepoint/team/blog).lists[2] | Format-Table Title, Id, 

ItemCount, hasUniqueRoleAssignments, EnabledAttachments, EnableThrottling

In the preceding example, the value 2 is used, rather than 3, because developers like to start counting at 0. Therefore, the first item in the collection is number 0, and the third item is 2.

As mentioned previously, you can also get a list by using the Id or list title. Simply replace the number 2 with the Id or Title. Go ahead and try:

(Get-SPWeb http://sharepoint/team/blog).lists["Links"] | Format-Table Title, Id, 

ItemCount, hasUniqueRoleAssignments, EnabledAttachments, EnableThrottling

At this point, you know how to get down to the list level and enumerate all of your lists and libraries. Want to create a new list? Well, that one is a little tricky. First, you need to decide what type of list you will create. To keep it simple, the next example creates a Links list. The Links list template has an Id of 103, which is information you can find by looking in the SharePoint documentation. You can also get this information by running the following command:

(Get-SPWeb http://sharepoint/team/blog).ListTemplates | Where-Object {$_.Name –eq 

"Links"}

To create the Links list, you need to call the Add method of the List collection you have already been working with. The Add method requires three parameters for this example: Title, Description, and ListTemplateId. Armed with all of this information, add that list using the following command:

(Get-SPWeb http://sharepoint/team/blog).Lists.Add("Demo Links List", "This is the

 description", 103)

Figure 10-34 shows the new, improved list of lists — now with even more Links lists.

Finally, to close out this section you will delete your list. Yes, delete and not remove. The Delete method is a method of the SPListCollection object (the Lists property), and not a command in PowerShell, which is why you can use it. The Delete method of the List collection requires the list Id, so we are going to use a variable this time to grab the list Id in one line and use it in the Delete on the next line. Following are the two lines needed to delete the list you just created, and Figure 10-35 shows what it looks like.

$listId = (Get-SPWeb http://sharepoint/team/blog).lists["Demo Links List"].Id

(Get-SPWeb http://sharepoint/team/blog).lists.Delete($listId)

Again, you can verify that you did indeed remove the list by using the earlier command to list all your lists.

We can’t close out this section without at least pointing you new admin developers to the key documentation that will help you with these more interesting creations: the SharePoint 2010 SDK, or Software Development Kit. Don’t let the name scare you. It is actually a compiled help file or a set of web pages that provides documentation on the various objects in SharePoint. The SharePoint 2010 SDK is currently located at http://msdn.microsoft.com/en-us/library/ee557253(office.14).aspx. (Note that it might move later, as it contains “Office.14” in the URL. To find it after it is moved, simply search for “SharePoint 2010 SDK.”

Disposing of SharePoint Variables

No chapter on working with SharePoint and PowerShell would be complete without discussing a topic that just might keep your farm up and running: disposing of your SharePoint objects. It is no myth that certain SharePoint objects need to be disposed of properly or you might see memory leaks on your beloved farm.

Although a few variables slipped into the examples, this chapter specifically avoided scenarios that required their use. It instead focused on single-line commands, which includes commands that are chained using the pipeline, because single-line commands will properly handle the disposal of SharePoint objects. The more you stick to one-liners, the less chance you have to forget how to properly clean up after yourself.

The disposal issue becomes a problem as soon as you start to capture certain SharePoint objects such as SPSite, SPSiteAdministration, and SPWeb, and hold on to them. They cannot be disposed of at the end of the pipeline because you are still using the object.

Luckily, there are two commands to help you work with situations in which you might run into disposal issues: Start-SPAssignment and Stop-SPAssignment. The SPAssignment commands help you to both track objects and then dispose of them when they are no longer needed.

This section covers two different ways of using these commands. The first command is the simple assignment method that uses the Global switch parameter. Basically, before you start to use objects that might need to be disposed of, you call Start-SPAssignment using the Global switch parameter. This will start the tracking of all resources being used, which quite frankly can be a lot. Once you are done working with your variables and objects, you need to call Stop-SPAssignment with the same Global switch parameter. At this point, all the objects that were tracked will be released and properly disposed of. Once you call Stop-SPAssignment you should not use the resources for that block of commands, as they may not work properly as they are disposed of.

Figure 10-36 demonstrates the use of Start and Stop-SPAssignment with the Global switch parameter.

While using the simple assignment method is simple, it does have some drawbacks. Any trackable SharePoint object between the Start and Stop-SPAssignment will be managed by the commands. This means that if you run many one-liners that do not necessarily need to be tracked, they will get tracked anyway and that is more memory that is waiting to be released.

If you know when you need to track a SharePoint object, you can manually assign your resources to be tracked. This enables you to be selective regarding the objects that are assigned for tracking and disposal. You can do this with the same Start and Stop-SPAssignment commands. With this technique, you create a new SPAssignmentCollection using Start-SPAssignment — for example, $spAssign = Start-SPAssignment.

When you need to track objects, you can use the $SPAssign in the pipeline. For example, you can assign all webs from a particular site collection for tracking and disposal:

 $Webs = $SPAssign | Get-SPSite http://sharepoint | get-SPWeb

You can also throw in a few one-liners as we have been doing up until now. These do not need to be tracked because they will be disposed of properly. Since these objects will not be assigned to the SPAssignmentCollection object, they will be disposed of at the end of their lifetime and will not hold onto extra memory. Once you are done with your block of commands, you can clean up using the Stop-SPAssignment command, passing in the $SPAssign variable. Like the simple assignment, once you call Stop-SPAssignment you should not use the variables that were assigned to the SPAssignmentCollection. Figure 10-37 demonstrates the assignment of a collection of web objects and their proper disposal with the call to Stop-SPAssignment.

Note in Figure 10-37 that you do not assign the SPWeb object you used to display the SPList objects. This SPWeb object is in a one-liner and will be disposed of correctly without the need for any tracking.

Summary

This PowerShell thing just might catch on. As demonstrated in this chapter, it adds a dimension of power to SharePoint administration that just wasn’t available to administrators in SharePoint 2007. This chapter has taken you from being a PowerShell newbie to using advanced techniques on your SharePoint farm, such as looping and object disposal. While we don’t recommend talking to developers if it can be avoided, using PowerShell levels the playing field some. You’ll be able to tell amusing anecdotes about SPSites and SPWebs and they’ll laugh along. Oh, and you’ll be able to better administer your SharePoint 2010 farm too.

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

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