PART 1 WINDOWS POWERSHELL 101 03 X CHAPTER 2 FILTERING AND ITERATING YOUR DATA 39 X CHAPTER 3 MAKING YOUR POWERSHELL REUSABLE CO PY RI GH X CHAPTER 1 TE D MA TE RI AL Getting Started With Windows Powershell Basics 65
CHAPTER 1 Windows PowerShell 101 IN THIS CHAPTER, YOU WILL LEARN TO: X PREPARE FOR YOUR JOURNEY 4 Automate SharePoint: A Historical Perspective. . . . . . . . . . . . . . . . . .5 From STSADM to Windows PowerShell . . . . . . . . . . . . . . . . . . . . . . . . .7 X UNDERSTAND THE COMPONENTS 8 The SharePoint 2010 Management Shell. . . . . . . . . . . . . . . . . . . . . . . .8 Understand Required Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 1 M icrosoft’s latest version of its SharePoint platform, SharePoint 2010, introduces numerous new capabilities and architectural changes that make what was already a powerful platform even more powerful and, in doing so, much more complex and difficult to manage. As with the 2007 version of SharePoint, you can use the point-and-click administrative tools found in the SharePoint Central Administration website or you can use STSADM, SharePoint 2007’s command-line tool.
Before you dig deep into Windows PowerShell, it is a good idea to take a look at the other scripting options available to you, specifically STSADM and PSConfig, the command-line version of the SharePoint Configuration Wizard. This is useful because there are some tasks that can only be accomplished using STSADM (though not many). Automate SharePoint: A Historical Perspective When SharePoint 2003 was introduced, Microsoft made available the first version of STSADM.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 psconfig -cmd services -install if not errorlevel 0 goto errhnd ECHO %DATE% %TIME%: Installing features psconfig -cmd installfeatures if not errorlevel 0 goto errhnd ECHO %DATE% %TIME%: Creating central admin site psconfig -cmd adminvs -provision -port i %CENTRALADMIN_PORT% -windowsauthprovider enablekerberos if not errorlevel 0 goto errhnd ECHO %DATE% %TIME%: Adding app content to CA site psconfig -cmd applicationcontent -install if not errorlevel 0 goto errhnd
As you transition to SharePoint 2010, you will be pleased to note that all of the preceding scripts will work just fine (with the exception of the psconfig -cmd configdb command, which now requires a passphrase parameter).
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 next-generation scripting language and offers direct access to .NET objects, complex flow and structure capabilities, and an object pipeline that makes passing objects from one command to another extremely easy. STSADM and PSConfig are still part of the product, and every command that was still relevant to the product has remained (that is, commands pertaining to things such as the Shared Services Provider, which no longer exists, have been removed).
“ & ‘ i C:\...\PowerShell.exe -NoExit C:\...\14\CONFIG\POWERSHELL\Registration\sharepoint.ps1 ‘ “ The SharePoint 2010 Management Shell is just a Windows PowerShell instance that loads the sharepoint.ps1 script file. If you open this script file, you will see the following: $ver = $host | select version if ($ver.Version.Major -gt 1) { $Host.Runspace.ThreadOptions = “ReuseThread” } Add-PsSnapin Microsoft.SharePoint.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 you will now have the benefit of integrated debugging capabilities, syntax highlighting, and of course, a simple editor in which you can construct your routines without having to execute them line by line. An alternative to manually executing the Add-PsSnapin cmdlet would be to update your default user profile. This will enable you to use the SharePoint PowerShell cmdlets in any editor for any user.
T I P For more information on editing your user profile script, type help about_ profiles from any Windows PowerShell window or view the TechNet article “How to Create Profiles in Windows PowerShell ISE” at http://technet.microsoft.com/ en-us/library/dd819492.aspx. Understand Required Permissions Before you can use the SharePoint 2010 Management Shell (or specifically, the SharePoint 2010 cmdlets), you must have the appropriate permissions.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 In this case, http://sp2010:12345/ is the URL to the Central Administration site. Throughout the course of this book, we will assume that you are executing the scripts as a user with sufficient permissions. Namely, you are a Local Administrator or a Farm Administrator, and you have been granted Shell Administrator rights via the Add-SPShellAdmin cmdlet. In some cases, you should also be in the dbcreator and securityadmin roles within SQL Server.
U N D E R S TA N D T H E CO M P O N E N T S TimerService Property Microsoft.Share... TraceSessionGuid Property System.Guid Tra... TypeName Property System.String T... UpgradeContext Property Microsoft.Share... UpgradedPersiste... Property System.Collecti... Getting Started with Windows PowerShell Basics ... 13 Version Property System.Int64 Ve... PART 1 The Get-Member cmdlet takes in any object and outputs information about the object’s public methods and properties.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 In Windows PowerShell, an object’s type is represented by wrapping the object in brackets (for example, [type name]). This is most commonly seen when accessing a static method or property of a type, such as the LoadWithPartialName method or the Local property. However, rather than using a period to access the object member, you use a double colon (::). Types are explained in more detail later in this chapter.
can be especially difficult when that task requires the use of several cmdlets that must be executed in a specific order or when a specific cmdlet for the task doesn’t exist, thus requiring the use of the SharePoint object model. In most cases, the best way to locate the cmdlets or .NET objects, methods, or properties that you’ll need is to use the SharePoint software development kit (SDK), specifically the Index of SharePoint Server 2010 Windows PowerShell cmdlets (http://technet.microsoft.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 COMMON PARAMETERS Every Windows PowerShell cmdlet contains some common parameters. To see more information about those parameters, type help about_commonparameters. The common parameters are as follows: -Verbose -Debug -WarningAction -WarningVariable -ErrorAction -ErrorVariable -OutVariable -OutBuffer -WhatIf -Confirm You will see the common variables -ErrorAction, -ErrorVariable, and -Confirm used extensively in later parts of this book.
U N D E R S TA N D T H E CO M P O N E N T S Get-SPServiceApplicationProxy Getting Started with Windows PowerShell Basics Set-SPServiceApplication 17 Remove-SPServiceApplicationProxy PART 1 Unpublish-SPServiceApplication Remove-SPServiceApplication Publish-SPServiceApplication Get-SPServiceApplication Remove-SPServiceApplicationProxyGroup New-SPServiceApplicationProxyGroup Get-SPServiceApplicationProxyGroup Remove-SPServiceApplicationProxyGroupMember Add-SPServiceApplicationProxyGroupMember Get-SPSer
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 Once you have identified the cmdlets you need, you can then use the Get-Help cmdlet to learn more about how to use the cmdlets: PS C:\> Get-Help Start-SPServiceInstance NAME Start-SPServiceInstance SYNOPSIS Starts the service instance for a service on a specific ser ver or the farm.
For technical information, type: “get-help Start-SPServiceI nstance -full”. Eventually, you’ll get to the point where the available cmdlets fail you and you must resort to working with the object model. Again, the SDK is a great resource for you, but oftentimes, just seeing a list of available methods and properties is enough to get you started. You can use the Get-Member cmdlet to return a listing of all the properties and methods that you can work with.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 CMDLET ALIASES There are some cmdlets within Windows PowerShell that have built-in abbreviations known as an alias. For example, rather than typing Get-Command, you could simply type gcm, and similarly for Get-Member, you can type gm. There are numerous builtin aliases, and you can see them all by executing the Get-Alias cmdlet as shown.
Understand Variables and Types Now that you know the core components involved, you can begin to use Windows PowerShell to perform some tasks. The following sections will review the core Windows PowerShell elements that every SharePoint administrator must know. These include declaring and using variables and working with various data types, including the core value types as well as arrays and hash tables.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 While these names will work in Windows PowerShell, it is more common to see variables expressed using camel case. Camel case is a naming convention that has the first word lowercased and the first letter of each additional word capitalized.
In this example, we call the GetType() method of the string value “Tessa”. From this, you can see that “Tessa” is a fully qualified System.String object. ESCAPE CHARACTER Strings can be defined using either double quotes or single quotes.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 Windows PowerShell was able to convert the comma-separated list of items to an array dynamically. This is part of Windows PowerShell’s adaptive type system that facilitates the automatic conversion of one type to another. The Adaptive Type System To examine how the adaptive type system works, we start by looking at an earlier example: PS C:\> $farm = Get-SPFarm PS C:\> $farm.GetType().FullName Microsoft.SharePoint.Administration.
U N D E R S TA N D VA R I A B L E S A N D T Y P E S System.Xml.XmlDocument Getting Started with Windows PowerShell Basics >> 25 PS C:\> PART 1 >> >> “@ >> $config.GetType().FullName >> This interesting example demonstrates two concepts. The first is what is known as a here string.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 Look at this a little closer, and use the Get-Member cmdlet to see the details of the Farm property: PS C:\> $config.Farm | gm TypeName: System.Xml.XmlElement Name MemberType Definition ---- ---------- ---------- ToString CodeMethod static stri... AppendChild Method System.Xml.... Clone Method System.Xml.... CloneNode Method System.Xml.... CreateNavigator Method System.Xml.... Equals Method bool Equals...
WriteContentTo Method System.Void... WriteTo Method System.Void... Item ParameterizedProperty System.Xml.... AdminContentDB Property System.Stri... CentralAdmin Property System.Xml.... ConfigDB Property System.Stri... Getting Started with Windows PowerShell Basics U N D E R S TA N D VA R I A B L E S A N D T Y P E S DatabaseServer Property System.Stri... PART 1 FarmAccount Property System.Stri... Passphrase Property System.Stri...
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System... GetHashCode Method int GetHashCode() GetType Method type GetType() LookupName Method string LookupName() ToString Method string ToString() ValidateLogonAccount Method System.Void Valida... SecurityIdentifier Property System.Security.Pr... Name ScriptProperty System.Object Name... Notice that the Name property is of type ScriptProperty.
This collection can then be passed into most cmdlets, such as the Get-SPSite cmdlet: PS C:\> $siteUrls | Get-SPSite Url --http://portal http://teams PS C:\> In this particular example, the Windows PowerShell runtime is looping through each item in the array and calling the Get-SPSite cmdlet for each item. The objects written to the pipeline are then grouped together to form a new collection (an array of type object[]) that can then be passed into other cmdlets.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 Hash tables, also known as dictionaries, are declared by wrapping the list of semicolon-separated items in curly braces and defining a “key” for each item by setting the key equal to the value: PS C:\> $sites = @{“Portal” = “http://portal”; i “Team Sites” = “http://teams”} PS C:\> $sites Name Value ---- ----- Portal http://portal Team Sites http://teams PS C:\> The quotation marks around the key portion are only necessary if the name has a space in it.
WORK WITH OUTPUT http://mysites Getting Started with Windows PowerShell Basics PS C:\> $sites1.Portal 31 PS C:\> PART 1 http://portal PS C:\> $sites1.”Team Sites” http://teams PS C:\> $sites1[“My Sites”] Work with Output After you’ve declared and set your variable or executed a specific cmdlet, you’re likely to need to pass that information into another cmdlet or otherwise display the results to the console in some formatted fashion.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 -useremail someone@example.com -username “Your Name” stsadm.exe -o enumusers -url http://server/site/web The concept of passing data from one command to another is known as piping. The Windows PowerShell pipeline facilitates this movement of data between commands.
e. If you use a relative path, you must specify the Site parameter. A valid URL in the form http://server_name or a relativ e path in the form of /SubSites/MySubSite. Required? false Position? 1 PART 1 Default value Accept pipeline input? False Accept wildcard characters? false -AssignmentCollection Manages objects for the purpose of proper disposal.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 rver_name; a GUID, in the form 1234-5678-9807, or an SPSite object. Required? false Position? Named Default value Accept pipeline input? True Accept wildcard characters? false From this snippet, you can see that the Get-SPWeb cmdlet can take an SPAssignmentCollection object (which is discussed in Chapter 3) via the pipeline, but you cannot pass the Identity parameter via the pipeline.
WORK WITH OUTPUT $webs = $site | Get-SPWeb Getting Started with Windows PowerShell Basics The following example demonstrates how to use the SPSitePipeBind object with the Get-SPWeb cmdlet to return all the SPWeb objects within the specified site collection: 35 $webs = $site.
CHAPTER 1 • WIN DOWS POWE RSH E LL 101 These cmdlets offer a variety of techniques for outputting data, including the ability to specify which properties of the object you’d like to have displayed and the use of wildcards, regular expressions, and script blocks: PS C:\> $site = Get-SPSite http://portal PS C:\> $site | Format-List Url, Host*, i {[int]($_.Usage.Storage/1MB)} Url : http://portal HostHeaderIsSiteName : False HostName : portal [int]($_.Usage.
class SPSite { Url = http://portal HostHeaderIsSiteName = False HostName = portal [int]($_.Usage.Storage/1MB) = 5 PART 1 } The Format-Custom cmdlet provides an output similar to that of a class declaration for an object-oriented language. Its use is very limited, and most people favor the Format-List cmdlet over it. If you try the same command using Format-Wide, you’ll receive an exception because the Format-Wide cmdlet can take only one property at a time.