PowerShell SharePoint 2010 Learning Area 2

Examine and Document the SharePoint Logical Structure Using Windows PowerShell

Get-SPFarm

Get-SPWebApplication

To include the Central Administration Web application, add the parameter -IncludeCentralAdminsitration, as in the following example: Get-SPWebApplication –IncludeCentralAdministration

Get-SPSite cmdlet limits the number of site collections it returns to 20 by default. Add the -Limit parameter to increase this limit or add -Limit All to return all site collections.

The Get-SPWeb cmdlet, unlike Get-SPSite or Get-SPWebApplication, does not retrieve
a collection of website objects. Get-SPWeb followed by a URL returns an object that references a single website, as in the following example: Get-SPWeb http://intranet.contoso.com/sites/Sales/Blogs

Get-SPWeb followed by the -Site parameter retrieves a collection of websites in the specified site collection. Get-SPWeb –Site http://intranet.contoso.com  retrieves the websites in the intranet site collection

The Get-SPWeb cmdlet limits the number of objects it returns to 200 by default so use –Limit All to get all

Get-SPSite http://intranet.contoso.com  retrieves only one site collection

Get-SPSite "http://intranet.contoso.com" | Get-SPWeb -Limit All   retrieves all websites in the intranet site collection

Get-SPWebApplication "http://intranet.contoso.com" | Get-SPSite –Limit –All  list all site collections in the intranet web application,

Get-SPWebApplication "http://intranet.contoso.com" | Get-SPSite –Limit All |
Get-SPWeb -Limit All    enumerates all websites in the intranet web application

Get-SPWebApplication –IncludeCentralAdministration | Get-SPSite –Limit –All |
Get-SPWeb -Limit All    list all websites in the farm, including Central Administration

 

Discover Object Members (Methods and Properties)  Using Get-Member

Objects have members—most important, their methods and properties. Methods are actions—
things you can do with or to the object. Properties are attributes. A special kind of property is a collection, which can contain zero, one, or more items.  To discover what methods and properties are exposed by a particular object, pipe the object to the Get-Member cmdlet. Get-Member takes an object as input. The following commands list the members of an object: see Techne for more
object | Get-Member –MemberType Methods
object | Get-Member –MemberType Properties

Display Properties with Select-Object (Alias: Select)

You can change which properties are displayed at the end of the pipeline by using the
Select-Object cmdlet, which has the alias Select.
Get-SPWeb "http://intranet.contoso.com/sites/Sales/Blogs" | Select *

Get-SPWeb "http://intranet.contoso.com/sites/Sales/Blogs"| Select URL,WebTemplate,LastItemModifiedDate

Get-SPWebApplication | Get-SPSite -limit all | Get-SPWeb -limit all | Select-Object URL,WebTemplate

Note: you do not have to specify get spWeb.

| Sort WebTemplate use this to sort the list

Display Results with Format-Table and Format-List (Aliases: ft and fl)

Get-SPWebApplication | Get-SPSite -limit all | Get-SPWeb -limit all | Select-Object URL,WebTemplate | Sort WebTemplate | Format-List

NOTE FORMAT-LIST ADDS AN IMPLICIT SELECT *
Using Format-List (or fl) at the end of the pipeline adds an implicit Select *. All properties
are returned. If you want to limit properties returned, add the properties to the Select
cmdlet.

To save output to a CSV file, add | Export-CSV <filename> to the end of the pipeline

| ConvertTo-XML to the end of the pipeline to convert output to an XML object.
An XML object is not immediately viewable because it is an object, not the text output of an XML file. Therefore, you must save the pipeline, and thereby save the XML file. Follow this template:
( command | ConvertTo-XML ).Save("filename")

(Get-SPWebApplication | Get-SPSite -limit all | Get-SPWeb -limit all | Select-Object URL,WebTemplate | Sort WebTemplate | ConvertTo-XML).Save("C:\Users\SP_Admin\Desktop\SharePointWebsiteTemplates.xml")

Grid View and Out cmdlet

Windows PowerShell 2.0 includes an Integrated Scripting Environment (ISE), which
provides a datagrid view application. You must make sure that the Windows PowerShell ISE
feature is installed. If it is not, add the ISE feature by using Server Manager’s Add Features
Wizard. | Out-GridView -Title "Web Site Templates Report"  The correct way to structure this command is to put the Out-Host cmdlet at the end of the pipeline as shown below. This causes the process data to be formatted in a list before being paged and displayed. Good article here.

Paging

PS> Get-Command | Out-Host –Paging

You can also use the more function to page data.

In Windows PowerShell, more is a function that calls Out-Host -Paging. The following command demonstrates using the more function to page the output of Get-Command: PS> Get-Command | more

Filter the Pipeline with Where-Object (Aliases: Where, ?)

For example, the following command retrieves all websites in the farm that are based on the Blog site definition by using the WebTemplate property of the SPWeb object:

Get-SPWebApplication | Get-SPSite -Limit All | Get-SPWeb -Limit All | Where-Object { $_.WebTemplate -eq "BLOG"}

or

PS> Get-SPSite –Limit ALL | Get-SPWeb –Limit ALL |?{ $_.WebTemplate –eq “BLOG#0”}

The filter—the criterion against which websites are being evaluated—is an expression
surrounded by curly braces. The expression states that an object’s WebTemplate property must
be equal to “BLOG.” If a website fails to meet this criterion, it is removed from the pipeline.
Notice the use of the special variable, $_. The special variable $_ represents the current
object in the pipeline
. A collection of all websites in the farm is piped to Where-Object from
Get-SPWeb. Where-Object’s job is to filter the pipeline, allowing only websites that use the
blog template through the filter.  For more go to http://go.microsoft.com/fwlink/?LinkID=192743

Comparison Operator Meaning Example (returns true)

-eq

is equal to

1 -eq 1

-ne

Is not equal to

1 -ne 2

-lt

Is less than

1 -lt 2

-le

Is less than or equal to

1 -le 2

-gt

Is greater than

2 -gt 1

-ge

Is greater than or equal to

2 -ge 1

-like

Is like (wildcard comparison for text)

"file.doc" -like "f*.do?"

-notlike

Is not like (wildcard comparison for text)

"file.doc" -notlike "p*.doc"

-contains

Contains

1,2,3 -contains 1

-notcontains

Does not contain

1,2,3 -notcontains 4

 

Logical Operator Meaning Example (returns true)

-and

Logical and; true if both sides are true

(1 -eq 1) -and (2 -eq 2)

-or

Logical or; true if either side is true

(1 -eq 1) -or (1 -eq 2)

-not

Logical not; reverses true and false

-not (1 -eq 2)

!

Logical not; reverses true and false

!(1 -eq 2)

 

Server-Side Filtering Using –Filter

When you perform filtering using the Where-Object cmdlet, Windows PowerShell retrieves
all objects from the server and then filters the objects locally on the client computer. You can reduce the burden on the server by using server-side filtering. the following command retrieves the websites that are based on the Blog site definition by using server-side filtering of the SPWeb object:

Get-SPWebApplication | Get-SPSite -Limit All | Get-SPWeb -Limit All -Filter {$_.Template -eq "BLOG#0"}

above is faster than this one, –Fiter does server side filtering

Get-SPSite –Limit ALL | Get-SPWeb –Limit ALL |?{ $_.WebTemplate –eq “BLOG#0”}

The filter parameter support is as follows:

a. SPWeb supports: Title and Template

b. SPSite and SPSiteAdministration supports: Owner, SecondaryContact, and LockState

 

Other filtering examples

Get all sites under the “My” managed path in the “MySharePoint” web application
PS> Get-SPSiteAdministration “http://MySharePoint/my/*”

Regular Expression URLS (supported by Get-SPSite and Get-SPSiteAdministration).in the “identity” field and then giving the RegEx flag I will get all sites named “Demo1” under both the sites and teams managed path.
PS> Get-SPSite “http://MySharePoint/(sites|teams)/demo1 –RegEx

Filter Parameter for “special” properties (Supported by Get-SPSite, Get-SPSiteAdministration and Get-SPWeb). First I will get all Site Collections with “Contoso\JDoe” as the owner:
PS> Get-SPSite -Filter {$_.Owner –eq “CONTOSO\JDoe”}

Preferred more performant way to get all blog sites in a farm: PS> Get-SPSite -Limit All | Get-SPWeb -Limit All -Filter {$_.Template -eq "BLOG#0"}

Site Administration cmdlets are cmdlets that allow farm administrators to manage SPSites that they don’t have access to explicitly, will always allow a farm admin to configure some basic properties (owner, quota, etc) on a SPSite

Build an Effective Pipeline

As objects are passed through the pipeline of a Windows PowerShell command or script,
there is a common approach and order to working with those objects:
 Get     Use the Get verb to retrieve objects.
 Filter   Use the Where cmdlet to filter objects so that the only objects remaining in the pipeline
               are those with which you want to work. In the few cases where server-side
                 filtering is available, add a -Filter parameter to the Get commands.
Manipulate   Do something to the objects by using cmdlets appropriate for the type of objects in the pipeline.
Select Use the Select cmdlet to select the properties of objects that you want to output.
Sort Use the Sort cmdlet to sort the results, before output.
Output   Use the Format-*, Export-*, and Out-* cmdlets to produce output in the desired format.

 

Create a Web Application Using New-SPWebApplication

This command creates a new application pool. If the application pool already exists, you
would not include the -ApplicationPoolAccount parameter and value

New-SPWebApplication -Name "Contoso Intranet" -Port 80 -HostHeader "intranet.contoso.com" –URL "http://intranet.contoso.com:80" -ApplicationPool "SharePoint Web Applications" -ApplicationPoolAccount (Get-SPManagedAccount "CONTOSO\SP_WebApps") -DatabaseName "SharePoint_Content_Intranet"

Remove-SPWebApplication http://intranet.contoso.com -DeleteIISSite -RemoveContentDatabase -Confirm:$false

The -WhatIf parameter is particularly helpful when you are performing a command on a variable
or collection of objects so that you know exactly what is being done to which objects.

Create a Site Collection Using New-SPSite or Sub Site

For example, the following command creates a site collection at the root of the intranet web application and creates a top-level site with the Publishing site definition.

New-SPSite -Url "http://intranet.contoso.com" -Name "Contoso Intranet" –OwnerAlias "CONTOSO\SP_Admin" -Template "BLANKINTERNET#0"

Use –SecondaryOwnerAlias as well

-ContentDatabase to direct to certain db

Get-SPWebTemplate to list of template funny numbers

New-SPWeb "http://intranet.contoso.com/Blogs" -Name "Contoso Blogs" -Template "BLOG#0"

Variables $MyVariable

For example, the following script stops the SharePoint Timer service:
$service = "SPTimerV4"
Get-Service $service | Stop-Service

Iterate with ForEach-Object (Aliases: %, ForEach)

Many cmdlets automatically iterate, or loop, through objects in the pipeline. Look at the following example:
Get-SPWebApplication | Get-SPSite –Limit ALL | Get-SPWeb –Limit ALL  It iterates through each site collection, returning a collection of websites in that site collection. However, some cmdlets cannot operate on multiple objects. This is why the For-Each cmdlet is one of the most important cmdlets for working on multiple objects. ForEach-Object has a commonly used alias, ForEach, and another, super- abbreviated alias, %.

The ForEach-Object cmdlet iterates through each object in the pipeline, performing one or more actions that are contained in a script block. The script block is enclosed in curly braces. For example, the following command enables the Ratings feature for all site collections in the farm:

Get-SPWebApplication | Get-SPSite –Limit ALL | ForEach-Object { Enable-SPFeature "Ratings" -Url $_.url }

This command will only do one site collection, the above will loop through all
Enable-SPFeature "Ratings" -Url "http://intranet.contoso.com&quot;

This command will not work, this is why we use ForEach
Get-SPWebApplication | Get-SPSite –Limit ALL | Enable-SPFeature "Ratings"

Important Note: The ForEach-Object cmdlet, or its alias ForEach, typically operates in the middle of a pipeline, iterating through a collection of objects in the pipeline, and executing a script block for each object. The ForEach statement typically operates at the beginning of the pipeline, creating a collection of objects and then iterating through the collection, executing the script block for each object. So although ForEach-Object is piped the objects with which it works, the ForEach statement has its own objects—in this case, an array of string values of department names.
As a new Windows PowerShell user, you can take solace in the fact that the practical effect of the two is very similar. But the subtle differences between the statement and the cmdlet will arise as you learn more about Windows PowerShell, so it’s worth knowing that ForEach can be either a statement or a cmdlet.

 

Create Multiple Websites

$departments = ("HR", "Marketing", "Finance")
ForEach($dept in $departments)
{
New-SPWeb -Url http://intranet.contoso.com/$dept –Name "$dept" -Template "STS#0"
}

Note:  A blank line is at the end of the script. If you are entering the script directly in the Windows PowerShell console, you must enter a blank line to begin the execution of the script.

Read and Create Scripts

Windows PowerShell scripts can be entered directly in the console or saved as text files with a .ps1 extension.

In Windows PowerShell, the semicolon is used to combine separate commands into a single line. The following one-liner would generate websites for two more departments on the Contoso intranet:

$departments = ("Manufacturing", "Purchasing") ; ForEach($dept in $departments) { New-SPWeb -Url http://intranet.contoso.com/$dept –Name "$dept" -Template "STS#0" }

As you can see, combining lines makes a script difficult to read. It is a best practice to keep commands on separate lines.

Windows PowerShell will not execute a script by name only—it must know the path of the script. You can put a script in a folder that is included in the Path variable. Type $env:path to examine the current Path. If a script is in the Path, you can launch the script by name. Alternately, put the script in the current folder and type .\scriptname, or type the full path and filename of the script.

If a specified path or filename of a script includes a space, you must surround the path with quotes and precede it with the Call statement or its alias, &, as shown in the following example: & "C:\Scripts\My Folder\Script.ps1"

To execute a script from the Command Prompt, the Run command, or a scheduled task, use the following template: powershell.exe -noexit &’path\script.ps1’  The -noexit parameter causes the Windows PowerShell console to remain open after the script executes, so that you can observe the results of the script.

PowerShell Profile

SharePoint 2010 Management Shell loads a Windows PowerShell profile located in the
SharePoint root, by default: C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\14\CONFIG\POWERSHELL\Registration\SharePoint.ps1. A Windows PowerShell
profile is a script that configures the initial user environment for Windows PowerShell. It Loads the SharePoint snap-ins, Adds the Stsadm (SharePoint Root/BIN folder) to the path, Sets the PSThread option to ReuseThread.

You must also be a site collection owner, as defined in Central Administration, to use Windows
PowerShell against a site collection in the content database. To assign a site collection owner by using Windows PowerShell, follow this example:
Set-SPSiteAdministration <SiteCollectionURL> -OwnerAlias <DOMAIN\user> -SecondaryOwnerAlias <DOMAIN\user>

Advertisements