rilpoint_mw113

SharePoint 2010 PowerShell Cheat Sheet

Contents

PowerShell for SharePoint 2010

SharePoint 2010 ships with some 531 PowerShell cmdlets giving administrators ultimate power over their SharePoint server. This quick cheat sheet will help you get started with it.

Getting Started

SharePoint PowerShell “snapin” (command library) is installed on any server on which you performed a "complete" installation of SharePoint software (SharePoint 2010 front end server or application server). To start it locally:

  • On the Start menu, click SharePoint 2010 Management Shell,
  • Or in a regular PowerShell session, execute:
Add-PSSnapin Microsoft.SharePoint.Powershell

Permissions

To grant these permissions sufficient to use PowerShell for SharePoint 2010,use Add-SPShellAdmin cmdlet and specify the user and the databases to which the user needs access:

Add-SPShellAdmin -UserName contoso\velaskec -database (Get-SPContentDatabase -webapplication http://sitename)

For details see TechNet

Getting Help

  • Get help for a cmdlet:
Get-Help Get-SPSite
  • Get a list of all SharePoint cmdlets:
Get-Command -Module Microsoft.SharePoint.PowerShell
  • Wildcard search for a cmdlet:
Get-Command *Backup*
  • Finding out which properties and methods an object emitted by a cmdlet has:
Get-SPWeb | Get-Member

Remoting

To invoke cmdlets from a remote machine (for example, your workstation rather than SharePoint server) you can use PowerShell remoting.

  • To enable PowerShell remoting on the SharePoint server:
Enable-PSRemoting
  • To connect to the SharePoint server from your workstation in interactive mode:
Enter-PSSession 'MySharePointServer' -Credential:'Domain\Username' 
Add-PSSnapin Microsoft.SharePoint.Powershell
  • To execute a PowerShell script on a remote server from local machine without opening an interactive session:
$session = New-Session 'MySharePointServer' -Credential:'Domain\Username'
Invoke-Command $session { your script }

Implicit Remoting

  • To execute a PowerShell script on a remote server from local machine without opening an interactive session and typing Invoke-Command each time you can set up implicit remote session, in which case all SharePoint cmdlets will appear to be executing locally while in reality these will be so called "proxy functions" invoking their corresponding originals on the SharePoint server:
$session = New-PSSession 'MySharePointServer' -Credential:'Domain\Username'
Invoke-Command $session { Add-PSSnapin Microsoft.SharePoint.Powershell }
Import-PSSession -session $session
Get-SPSite "http://mycompany/sites/mysite"

Saving the remote session to local disk

PowerShell remoting also provides a method to save the remote session to a local disk module. Using this locally saved module, you can have quick access to the SharePoint cmdlets on a remote system. You can use Export-PSSession cmdlet to do this.

$session = New-PSSession 'MySharePointServer' -Credential:'Domain\Username'
Invoke-Command $session { Add-PSSnapin
Microsoft.SharePoint.Powershell }
Export-PSSession -Session $session -OutputModule "SP2010" -CommandName *-SP*

This will create a module by name SP2010 at the $env:PSModulePath. You can import this module like any other PowerShell module using Import-Module and get access to the remote cmdlets as if they were on the local machine. PowerShell takes care of creating a remote session as required and you will be prompted for the credentials to connect to a remote session, if required.

Gotchas

There are a few SharePoint gotchas to keep in mind:

  • Remote command may fail because of memory limits. To extend memory limits for remote sessions execute the following (on SharePoint server):
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1000

This needs to be executed under the account of local administrator. Otherwise it fails with "Access Deny" error.

Enable remote work with backend server

If your backend server is different than the frontend server to which you open remote session you need to enable CredSSP for access delegation.

  • To enable client-side SSP for winrm, run the following lines:
Enable-WSManCredSSP -Role client -DelegateComputer *
  • To enable server-side SSP for winrm:
Enable-WSManCredSSP -Role server
  • You can use CredSSP as the value to -Authentication parameter of Invoke-Command, Enter-PSSession, and New-PSSession cmdlets. This will enable delegating the credentials from client system to the server and other hops as required. More information available here: Download

Object disposal

By default, SharePoint PowerShell tends to dispose the objects at the end of the pipeline. This means that variables assigned to pipeline output might lose data once the one-liner is finished.

  • If you need the data to persist in memory and want to make SharePoint PowerShell store results beyond one-liners run:
Start-SPAssignment
  • To get back to default behavior (dispose once the pipeline is finished):
Stop-SPAssignment

Working with Sites and Lists

  • To get the number of site collections:
(Get-SPSite).Count
  • To remove all site collections:
Get-SPSite | Remove-SPSite
  • To remove all site collections without confirmations:
Get-SPSite | Remove-SPSite -Confirm:$false
  • To create a new site collection:
New-SPSite $url -OwnerAlias $admin -Template (Get-SPWebTemplate | Where {$_.Title -eq "Team Site" } )
  • To create new site:
New-SPWeb $url -Template (Get-SPWebTemplate | Where {$_.Title -eq "Team Site" })
  • To create new task list in all sites:
Get-SPWeb | ForEach {$_.Lists.Add("My Tasks", "", $_.ListTemplates["Tasks"])}
  • To create new task list in site:
Get-SPWeb $url | ForEach {$_.Lists.Add("My Tasks", "",$_.ListTemplates["Tasks"])}
  • To enumerate available workflows:
Get-SPWeb $url | Select -Expand WorkflowTemplates | Select Name
  • To enumerate all document libraries in your site:
Get-SPWeb $url | Select -Expand Lists | Where {$_.BaseType -eq "DocumentLibrary"}

SharePoint Timer Jobs

SharePoint delays execution of some of its tasks using timers. These may fail or be set up to execute too often and overload the server thus making other tasks fail.

  • To get a list of all timer jobs:
Get-SPTimerJob
  • To get a list of job failures grouped by the job name:
Get-SPTimerJob | Select -Expand HistoryEntries | Where {$_.Status -ne "Succeeded"} | group JobDefinitionTitle

Working with Content

  • Show all items in a site:
Get-SPWeb $url | Select -Expand Lists | Select -Expand Items | select Name, Url
  • Show only documents:
Get-SPWeb $url | Select -Expand Lists | Where {$_.BaseType -eq "DocumentLibrary"} | Select -Expand Items | select Name, Url
  • Search for item:
Get-SPWeb $url | Select -Expand Lists | Select -Expand Items | Where {$_.Name -like "*.doc"} | select Name, Url
  • To create a new document in a document library:
function New-SPFile($WebUrl, $ListName, $DocumentName, $Content)
{
$stream = new-object System.IO.MemoryStream
$writer = new-object System.IO.StreamWriter($stream)
$writer.Write($content)
$writer.Flush()
Get-SPWeb $WebUrl | ForEach {$_.Lists[$ListName]} | ForEach {$_.RootFolder.Files.Add($DocumentName, $stream, $true);$_.Update()}
}
New-SPFile -WebUrl "http://mycompany/sites/mysite" -ListName "Shared Documents" -DocumentName "MyFirstDocument" -Content "Power Blues"

Recycle Bin

  • To find an item by its name in the Recycle Bin for a site:
(Get-SPWeb "http://sp2010dc" ).RecycleBin | Where {$_.Title -match "cool"}
  • Then use the item ID to restore it:
(Get-SPWeb "http://sp2010dc" ).RecycleBin.Restore( "b23d2d41-cd6a-4471-a89 1 -c86f83563e11" )
  • For Site Collection Recycle Bin use:
(Get-SPSite).RecycleBin

SharePoint Backup

  • To start a full farm backup
Backup-SPFarm -BackupMethod Full -Directory "Destination-Directory" -BackupThreads 5

When the above command is executed, a full farm backup will be performed with five threads to perform the backup. You can specify up to 10 threads. However, the fewer the backup threads, the easier it is to read the backup log file. You can also specify "Differential" as the backup method to perform differential backup of SharePoint farm. By default, this does not show the progress of backup operation.

  • To see the progress as backup is performed:
Backup-SPFarm -BackupMethod Full -Directory "Destination-Directory" -BackupThreads 5 -Verbose
  • To see a list of all items included in backup:
Backup-SPFarm -ShowTree
  • To perform a site collection backup:
Backup-SPSite -Identity "http://MySite:2131/" -Path "Path to Backup file"
  • To perform on site collection backup using SQL snapshots:
Backup-SPSite -Identity "http://MySite:2131/" -Path "Path to Backup file" -UseSqlSnapShot

There is no option in the central administration to perform backup using SQL snapshots. This can be done using PowerShell only. Also, using SQL Snapshots is the recommended way to perform a site collection backup. This will allow users to continue to read / write site collection content while the backup is in progress.

Useful Links

Free PowerShell community, forums, administrative and scripting/debugging tools: PowerGUI.org Get latest version of this cheat sheet at: PowerGUI Cheat Sheet

Contributors

Skin by RIL Partner