Using PowerShell with SharePoint Foundation 2010

In previous versions of SharePoint, many administrative tasks were completed through the command-line tool, stsadm. This tool was not only used by administrators, it was used by developers who needed to add, deploy, upgrade, or delete solutions in the environment.

However, stsadmn has been replaced in SharePoint Foundation by PowerShell as the preferred command-line tool. stsadm has not totally been removed; it remains as a part of SharePoint to support compatibility with previous versions of SharePoint. Several stsadm commands have been added, and some have been removed. Even though stsadm still exists, it is recommended that any command-line operations be handled with PowerShell.

PowerShell Basics

PowerShell is a command-line scripting tool that provides administrators and developers full access to applications programming interfaces (API). This is very powerful for Share-Point 2010 because it allows you to create scripts that interact with lists, sites, Site Collections, and many other components of a SharePoint environment. PowerShell can be used to create complex or simple automated processes.

One interesting thing to note is that PowerShell is written on top of the .Net Framework. However, it still does take advantage of some of the functionality related to cmd.exe, which allows it to have more flexibility over traditional command line tools.

Windows PowerShell utilizes the concept of a cmdlet for its scripts. A cmdlet consists of at least two components, a command and an object, and has the ability to accept as well as return .NET objects. Another thing to note is because a cmdlet can return objects, it also provides the ability for one cmdlet to pass an object to another cmdlet. This allows for complex cmdlets to be created.

PowerShell is a prerequisite for SharePoint Foundation 2010 and will by default, be installed on your development computer. Also, once the SharePoint Installation is complete, a custom PowerShell console is created called the SharePoint 2010 Management Shell, which executes commands from a PowerShell profile file, sharepoint.ps1 before presenting you with a command prompt. The main aim of the SharePoint profile file is to load the PowerShell for SharePoint snap-in so that you can then use the new cmdlets specific to SharePoint. The SharePoint profile file contains the following code, plus a signature:

$ver = $host | select version
if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

This code obtains the version of PowerShell, checks that it is greater than 1, and then if that is true, it sets the threading model so that the first thread will be reused, loads the SharePoint PowerShell snap-in, and then changes directory to the home folder, such as C:users<userid>, where userid is the person who is currently logged on.

Tip

INSIDE OUT Managing the disposal of SharePoint objects when using PowerShell

Running each command, function, or script in the first thread mitigates many of the memory leaks that occur. However, the care you undertake when writing SharePoint code that implements the IDisposable interface, you must also take when calling such objects with PowerShell. These are the objects that represent sites, Site Collections, and the site administration object. Hence, the two SharePoint cmdlets that you should learn to use are the Start-SPAssignment and the Stop-SPAssignment. These relate to the –SPAssignmentCollection parameter that you might see used with a number of Share-Point cmdlets to return a “disposable object.”

You can see an example of how to use the Start-SPAssignment and Stop-SPAssignment cmdlets in Chapter 14. In that example, they were used in a script that applies a Theme to all sites in a Site Collection.

You can also dispose of the objects as you would in code by using the Dispose() method, as shown in the following example, that alters the MasterURL property of all sites in a Site Collection:

$scURL = "http://wideworldimporters";
$sc = Get-SPSite $scURL;
$sc.AllWebs | foreach {
  $spWeb = $_.
  $spWeb.MasterUrl = "/_catalogs/masterpage/SPFIO.master";
  $spWeb.Update();
  $spWeb.Dispose();
}
$sc.Dispose();

PowerShell contains an extensive built-in Help system, and you can access it quickly by typing help at the command-line interface. This is an alias for the cmdlet Get-Help. To find more information on the SPAssignment cmdlets, type Get-Help Start-SPAssignment in the SharePoint 2010 Management Shell.

Creating Cmdlets for SharePoint Foundation 2010

SharePoint Foundation 2010 contains over 240 SharePoint-related cmdlets. The exact number can be found by typing the following command:

@(Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell").count

These cmdlets provide functionality in the following areas:

  • Backup and recovery

  • Databases

  • Features and solutions

  • General

  • Import and export

  • Logging and events

  • Performance

  • Security

  • Service application

  • SharePoint Foundation 2010 Search

  • Site management

  • Timer jobs

  • Upgrade and migration

  • Workflow management

PowerShell cmdlets will be the standard command-line tool for administrative operations going forward in SharePoint. They are very beneficial to developers, as well, because developers can use them to deploy and remove solution packages in their development environments. In particular, the following commands are some that developers will find useful:

  • Add-SPSolution Uploads a SharePoint solution package to the farm

  • Install-SPSolution Deploys an installed SharePoint solution in the farm

  • Update-SPSolution Upgrades a deployed SharePoint solution

  • Uninstall-SPSolution Retracts a deployed SharePoint solution

  • Remove-SPSolution Removes a SharePoint solution from a farm

To get the complete list of SharePoint cmdlets installed on your environment, you can run the following command from your SharePoint 2010 Management Shell:

gcm -pssnapin microsoft.sharepoint.powershell |
  select Name, Definition | fl > .filename.txt

In general, cmdlets use a verb-noun pair. The noun specifies the object about which you want information or that you want to manipulate, and the verb states what you want to do with that object. The verbs and nouns are always separated by a hyphen with no spaces, and SharePoint cmdlet verbs have a prefix of SP. When you design SharePoint-specific cmdlets, always do the following:

  • Maintain a consistent naming standard for your cmdlets. For example, prefix your cmdlet verbs or nouns with two or three characters that represent your organization.

  • Define cmdlet nouns.

  • Define cmdlet noun properties.

  • Define cmdlet verbs and parameters.

  • Define your cmdlet errors, progress, and pipeline.

  • Implement the IDisposable interface for objects that are not disposed.

  • Provide help functionality.

When you follow this process, the set of cmdlets that you are developing will be meaningful and comprehensive.

Define Cmdlet Nouns

Define Cmdlet Nouns

To define cmdlet nouns, perform the following:

  • When you define a cmdlet noun, be very clear about the artifact it will manipulate. Think of nouns used SharePoint Foundation cmdlets and the names of SharePoint objects that the system administrator manages, such as the out-of-the-box objects: SPSite or SPWeb or SPFeature. Try not to create a new name for a noun if one already exists for that object, because this can be confusing to administrators, and just as with any development, do not develop a cmdlet for functionality that already exists. Also if administrators are heavy users of the Get-Help cmdlet to search for SharePoint cmdlets that manage SharePoint objects, such as using the command, Get-Help *SPSite*, then ensure that you use the commonly used filter characters as part of your nouns. To list all SharePoint related nouns, type the following:

    gcm -PSSnapin "Microsoft.SharePoint.PowerShell" |
     sort noun | group noun | more

    As a general rule, it is better to have a greater number of nouns that have fewer properties than to have a small number of nouns that have a great many properties. Any noun that has more than 15 properties is overburdened.

  • Identify the nonpersisted runtime state information that you want to expose to system administrators. Also, identify state information that may not be persisted but must nevertheless be returned to system administrators, for example, the running state of a service.

  • Evaluate whether a newly defined noun should be split into two or more different nouns. Create separate nouns for items that are semantically distinct. Use Feature or component specifications to identify whether a noun spans multiple concepts or features.

  • If a noun spans multiple data sources, either physical or logical, split the noun along data-source boundaries. Identify a logically independent subset of properties that is persisted in a single database or SharePoint object only. In most cases this subset should become a separate noun, but only if the resulting nouns are logically independent and only if they can be clearly understood as distinct entities (that is, easily separated) without confusing system administrators.

  • For every persisted data source object that is used by more than one noun, unify these nouns into a single noun. Also, unify nouns whose primary difference is that they have different lifetimes, because their creation and deletion can be managed separately.

Define Cmdlet Noun Properties

To define cmdlet noun properties, perform the following:

  • Define an Identity property. All nouns must have an Identity property whose value is unique and immutable, such as a GUID, and make this identity property the default property.

  • Create a pipebind for the noun. The pipebind should combine all properties that can uniquely identify the object.

  • Define the complete set of public properties for the noun. Treat the noun definition as though it were a public API. All related public properties are exposed in the command line when an instance of the noun is returned.

  • Define a data type for each property. Properties should be strongly typed so that format validation code can be attached to the property type rather than to the noun. For example, a property that represents an email address should be of type email address rather than of type String.

  • Identify atypically large properties. Ensure that unusually large properties (larger than 10 KB) are split into two or more properties.

  • Identify collections of properties that have a large number of elements (for example, a collection with more than 100 elements). Remove such large property collections and split the elements into separate nouns. Then, define the New, Remove, Get, and Set verbs for the new nouns.

    For example, consider a scenario in which Users is a property of a SPWeb object, which can have a large number of elements. To avoid problems, a separate noun called SPUser exists, that represents one element in the list, then associated with the SPUser noun is the New, Remove, Get, and Set verbs. Also because it makes sense with this object, there is another verb associated with the SPUser object: Move.

Define Cmdlet Verbs and Parameters

Determine which of the base verbs (Get, Set, New, Remove) apply to your noun. At a minimum, system administrators must be able to get settings and to change (or Set) them. Additionally, administrators might also need to create new instances (New) and delete existing ones (Remove):

Tip

INSIDE OUT Verbs used by SharePoint cmdlets

To find all the verbs that the out-of-the-box SharePoint cmdlets use, type the following command:

Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" | sort verb |
group verb | sort count -descending
  • Define the behavior of your Get cmdlet.

    The Get verb must retrieve all instances if no parameters are specified, and it must do so by writing the instances to the PowerShell pipeline. However, any operation that can potentially return a very large result set should include a Limit parameter for which a default limit is specified. Of course, when limiting a result set in this way, you must alert users that additional results might be excluded from the limited result set.

    The Get verb must have an Identity parameter. When specified, the corresponding cmdlet must return only the instance associated with that identity. If the identity that is specified is not unique, the cmdlet should return all instances that have the specified identity value.

    The Get verb can have additional optional filtering parameters. For example, the cmdlet Get-SPSite has a ContentDatabase parameter that restricts the result set to the Site Collections that are located in a specified content database. Furthermore, the Get verb must have a Server parameter if the cmdlet returns local (that is, computer-specific) configuration information.

  • Define the behavior of the Set cmdlet.

    The Set verb must have an Identity parameter to identify the instance that is being changed. The parameter must be able to take either an identity (for example, a GUID) or a name. If a name is specified and this name matches more than one instance, the cmdlet must return an error.

    The Identity parameter of the Set cmdlet must accept pipeline input.

    The Set verb must expose all writable properties of the noun that are received using the corresponding Get cmdlet, except those that cause negative effects when set.

    The Set verb must have an optional Instance parameter that represents an entire instance of this noun type. The Instance parameter must accept pipeline input (by value).

  • Define the behavior of the New cmdlet.

    The New verb must take a limited subset of the writable properties of the noun as parameters. The remaining properties should be set to default values. Furthermore, the New cmdlet must return the newly created instance object to the pipeline so that further cmdlets in the pipeline can act on the new instance.

  • Define the behavior of the Remove cmdlet.

    Your Remove cmdlet must have an Identity parameter that can take either an identity value or a name. If a name is specified and it matches more than one instance, the cmdlet must return an error.

    The Identity parameter must accept pipeline input. Furthermore, any destructive operation must support Confirm and WhatIf parameters. This requires little effort, as PowerShell and base classes of SharePoint Foundation 2010 provide the means for supporting these parameters.

  • Identify and define additional verbs for the noun.

    For example, a SPContentDatabase noun might need a Mount verb to support mounting the specified database. Use well-tested administrative scenarios and use cases to support selecting appropriate verbs.

    Remember that all additional cmdlets must have an Identity parameter that accepts pipeline input. The Identity parameter must accept the identity (PipeBind) of the object. Furthermore, any destructive operation must support Confirm and WhatIf parameters.

  • Identify properties that have potential negative side effects.

    Properties that have potential negative side effects might require additional operations to mitigate the negative effects. These additional mitigating cmdlets must have an Identity parameter that accepts pipeline input.

  • For each cmdlet that you define, perform the following:

    • Identify the list of prerequisites for the cmdlet. For example, in a case where a cmdlet can be executed only in a certain system state, the cmdlet must verify that all state prerequisites are met before executing.

    • Identify the list of operations. Specify the complete list of operations that the cmdlet is able to perform. The cmdlet must perform and then validate these operations. This operation list comprises the functional breakdown of the cmdlet.

Define Cmdlet Errors, Progress, and Pipeline

To define cmdlet errors, progress, and pipeline, perform the following:

  1. Identify all error conditions and error-state behaviors. That is, list all conditions in which a cmdlet can error out. Then, for each condition, describe the expected behavior. Your cmdlets must provide basic error management.

    Your cmdlets must clean up partial changes when an error occurs, and they must return a meaningful (and localized, if appropriate) error message. Furthermore, cmdlets must determine and reveal how a system administrator can recover from any error condition.

  2. Differentiate between terminating and non-terminating errors.

  3. Identify long-running operations. If a cmdlet is expected to take longer than about twenty seconds, on average, to complete an operation, the cmdlet must provide progress information to avoid the appearance of a suspended operation.

  4. Ensure that cmdlets write their return objects directly to the pipeline. Avoid buffering retrieved objects to an internal array. Writing to the pipeline allows the downstream cmdlets to act upon preceding objects in the pipeline without delay.

  5. Group similar parameters. Limit cmdlets to sixteen parameters (not including the Identity and Name parameters). In cases where object methods are rarely called, and where an object model method exists, no cmdlet parameter is needed. In cases where a large number of parameters can be grouped, write a single parameter that accepts the group object.

Note

For more information about cmdlet development and guidelines, go to http://msdn.microsoft.com/en-us/library/ms714657(v=VS.85).aspx.

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

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