The
set of 500+ PowerShell cmdlets that come with SharePoint enable you to
perform a wide range of SharePoint administration tasks. But for
complete automation of SharePoint administration, some areas are not
covered via built-in cmdlets. In this section, we explore how we can
extend PowerShell beyond its original programming.
Creating Custom Functions with PowerShell
Custom functions in PowerShell enable developers to easily group sections of code together for easier and repeated usage.
Here is a simple HelloWorld function:
Function HelloWorld()
{
Write-Host "Hello World!"
}
To execute this function, type the following:
The easiest way to get
started with functions is with PowerShell ISE and execute the code
directly from the ISE. In case the ISE is not available, save the code
to a ps1 file with any text editor, such as Notepad. Execute it from a
PowerShell shell by typing
Functions and Parameters
When creating a PowerShell
function, you can define a number of parameters that need to be passed
when a function is called from the code; the simplest version of a
PowerShell function with parameters is the following:
Function HelloWorld($YourName)
For more flexibility with parameter properties, use the param syntax:
Function HelloWorld
{
Param (
[Parameter(Mandatory=$true)]
[string]$YourName ="John Smith",
[int]$YourAge = 0
)
Write-Host "$YourName ($YourAge)"
}
With the preceding
syntax function, an author can define which parameters are required,
variable types for each variable, and default values. Functions with
parameters can be called as shown next. When passed, parameters are
separated with spaces only; commas are not used:
HelloWorld "John Smith" 47
HelloWorld –YourAge 47 -YourName "John Smith"
Using the SharePoint .NET API to Extend PowerShell
The set of built-in
SharePoint PowerShell cmdlets enable you to manage your SharePoint farm,
all the features, site collections, and sites. These cmdlets do not
give you access to SharePoint lists, pages, workflows, and so on. This
limitation can be easily overcome by using the existing SharePoint .NET
API.
To
use the additional API (SharePoint, in this example) functions, API
must be referenced before using its objects and functions:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Retrieving SharePoint Lists with PowerShell
The following example
shows how to get a list of SharePoint lists and libraries on a
SharePoint site. To display such a list, a custom function is needed:
function Get-SPList
{
param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true
)]
[Microsoft.SharePoint.SPWeb]$CurrentWeb,
[Parameter(
Position=1,
Mandatory=$false
)]
[string]$Title = $null
)
foreach($list in $CurrentWeb.Lists)
{
if($list.Hidden -eq $false -and ($Title -eq $null -or $Title -eq ""))
{
Write-Output $list
}
elseif($list.Title -eq $Title)
{
Write-Output $list
}
}
The preceding function receives SPWeb
as the object and then invokes the appropriate functions from
SharePoint API to retrieve lists (only those available on the Quick
Launch menu).
To call this function, type the following:
Get-SPSite | Get-SPWeb -Limit ALL | ForEach-Object {Get-SPList -CurrentWeb $_} | Select ParentWeb, ParentWebUrl, Title, DefaultViewUrl
The Get-SPSite cmdlet lists all site collections (SPSite), pipes the results to Get-SPWeb that lists every site (SPWeb) within the site collection. Finally Get-SPList lists every list (only visible lists; system lists are usually hidden) in each of the sites found. The "-Limit ALL"
parameter is optional and should not be switched on for large farms. To
display only lists within a single site, use the following code:
Get-SPWeb "http://portal.companyABC.com/A-Project-Site" | ForEach-Object {Get-SPList $_} | Select ParentWeb, ParentWebUrl, Title, DefaultViewUrl
Creating New Lists and Document Libraries
Administrators can combine
the built-in PowerShell cmdlets with the SharePoint .NET APIs to create
lists and document libraries on-the-fly. Use the following code sample:
function New-SPList()
{
param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true
)]
[Microsoft.SharePoint.SPWeb]$SPWeb,
[Parameter(
Position=1,
Mandatory=$true
)]
[string]$Title,
[Parameter(
Position=2,
Mandatory=$false
)]
[string]$Description = "",
[Parameter(
Position=3,
Mandatory=$false
)]
[string]$ListTemplateType = "DocumentLibrary"
)
$SPWeb.Lists.Add($Title, $Description, $ListTemplateType)
}
To call the above given function type the following:
Get-SPWeb "http://portal.companyABC.com/A-Project-Site" | New-SPList -Title "Sample Doc. Lib" -Description "Doc. Lib. Sample"
Get-SPWeb " http://portal.companyABC.com/A-Project-Site " | New-SPList -Title "Sample Custom List" -Description "Custom List Sample" -ListTemplateType "GenericList"
Get-SPWeb " http://portal.companyABC.com/A-Project-Site " | New-SPList -Title "Sample Calendar" -Description "Calendar Sample" -ListTemplateType "Events"
The preceding sample creates three lists on a SharePoint site (“http://portal.companyABC.com/A-Project-Site”). The function New-SPList takes three parameters: Title, Description, and ListTemplateType. You must supply a unique title for a list within one site; to pass an appropriate template value, take a look at SPListTemplateType. For more information, refer to the following URL:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype(office.14).aspx
Modify List Properties
Let’s consider the following
scenario: a site owner wants to uniform versioning settings for all
lists and libraries in the site farm. A combination of PowerShell and
API comes to the rescue in such a scenario. To achieve that, we can
combine existing Get-SPSite and Get-SPWeb cmdlets with a custom function:
function Set-SPList()
{
param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true
)]
[Microsoft.SharePoint.SPList]$SPList,
[Parameter(Mandatory=$false)]
[bool]$EnableVersioning = $null,
[Parameter(Mandatory=$false)]
[bool]$EnableMinorVersions = $null,
[Parameter(Mandatory=$false)]
[int]$MajorVersionLimit = -1,
[Parameter(Mandatory=$false)]
[int]$MajorWithMinorVersionsLimit = -1
)
if($SPList -ne $null)
{
if($EnableVersioning -ne $null)
{
$SPList.EnableVersioning = $EnableVersioning
}
if($MajorVersionLimit -gt -1)
{
$SPList.MajorVersionLimit = $MajorVersionLimit
}
if($SPList.BaseType -eq "DocumentLibrary")
{
if($EnableMinorVersions -ne $null)
{
$SPList.EnableMinorVersions = $EnableMinorVersions
}
if($MajorWithMinorVersionsLimit -gt -1)
{
$SPList.MajorWithMinorVersionsLimit = $MajorWithMinorVersionsLimit
}
}
$SPList.Update()
}
}
If an administrator needs to
enable five major versions, and keep minor versions for three last major
versions, the function needs to be called like this:
Get-SPSite | Get-SPWeb -Limit All | ForEach-Object {Get-SPList $_ | ForEach-Object
{Set-SPList $_ -EnableMinorVersions $true -EnableVersioning $true -MajorVersionLimit
5 -MajorWithMinorVersionsLimit 3}}
Creating List Items On-the-Fly
When building
demonstration and presentation sites, a function that might come in
handy is the PowerShell function for creating items in a list. The
following sample shows how you could build such a function. It creates a
list item in a custom list and assigns only a title for the list item,
but it could be extended to create more complex items:
Function New-SPListItem()
{
param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true
)]
[Microsoft.SharePoint.SPList]$SPList,
[Parameter(
Position=1,
Mandatory=$true
)]
[string]$Title
)
[Microsoft.SharePoint.SPListItem] $listItem = $SPList.Items.Add();
$listItem["Title"] = $Title
$listItem.Update()
}
You can use the preceding function by typing the following:
Get-SPWeb "http://portal.companyABC.com/A-Project-Site" | Get-SPList -Title "The Team" | New-SPListItem -Title "John White"
Get-SPWeb "http://portal.companyABC.com/A-Project-Site" | Get-SPList -Title "The Team" | New-SPListItem -Title "Ann Green"
Get-SPWeb "http://portal.companyABC.com/A-Project-Site" | Get-SPList -Title "The Team" | New-SPListItem -Title "Zoey Gray"
The preceding code creates three new items (John White, Ann Green, Zoey Gray) in the list "The Team" located on the site “http://portal.companyABC.com/A-Project-Site”.
Managing Backend Systems with PowerShell
PowerShell can also
manage backend systems in the SharePoint environment. Microsoft and
third-party vendors released numerous packs to manage various systems,
and the most important ones for SharePoint environment are management
packs for IIS, Windows servers, and Active Directory.
Windows PowerShell Snap-In for IIS 7.5
Microsoft released a
PowerShell snap-in for IIS that can help administrators automate most
common operations with IIS sites and pools. SharePoint administrators in
complex environments can benefit from the ability to automatically
reset individual websites, recycle application pools, backup IIS
configuration, and so on.
The IIS snap-in can be downloaded from the following URL:
http://www.iis.net/expand/PowerShell
After downloading, follow the onscreen instructions to install the snap-in.
To use the snap-ins from this pack, it must be added; type the following:
Add-PsSnapin WebAdministration
This snap-in is no different from the SharePoint one; use Get-Command and Get-Help to learn more about cmdlets. Use the following code to list all web applications and pools:
# Lists all web applications (sites and pools) on IIS Get-WebApplication
# Lists names of all web sites that are stopped Get-WebSite | Where {$_.State -eq "Stopped"} | Select Name
Commands with Start, Stop, and Restart
verbs enable administrators to perform those actions against websites
and pools. To reset a SharePoint central administration pool, type the
following:
# Restarts the Central Administration application pool
Restart-WebAppPool "SharePoint Central Administration v4"
Windows PowerShell Server Management Cmdlets
PowerShell cmdlets for
managing Windows servers are built in to the PowerShell core and do not
need to be loaded separately. In SharePoint environments, you can use
them to control, for example, SharePoint Windows services, file systems,
and so on.
The following command lists
all SharePoint and ForeFront services currently stopped (ForeFront
services are used to sync user accounts):
Get-Service | Where {($_.DisplayName -like "*SharePoint*" -or $_.DisplayName -like "*ForeFront*") -and $_.Status -eq "Stopped"}
To start a service, type
Start-Service ("SharePoint 2010 Timer")
Automate User Provisioning with PowerShell
The built-in SharePoint
PowerShell cmdlets enable you to easily manage users across site
collections, but the real power of PowerShell is revealed when you
combine these with Active Directory management cmdlets.
The most common
usage scenario for user provisioning occurs when a new user exists in
CompanyABC.com. In this scenario, each new employee must be given an AD
account and contributor rights to the SharePoint site at http://portal.companyABC.com.
Here is how a new employee
procedure could be automated with PowerShell. Use the following sample
code to create a new AD account:
New-ADUser -Name "JohnS" -GivenName "John" -Surname "Smith" -DisplayName "John Smith" -AccountPassword (ConvertTo-SecureString "pass@word1" -AsPlainText -force) -Enabled $true
To completely automate importing from PowerShell, use the Import-CVS cmdlet that enables automatic imports to be done from a CSV file. New-ADUser has more parameters that you can specify on account creation, but these are beyond the scope of this book.
When you have a new user created in Active Directory, you can use existing SharePoint cmdlets to assign proper user privileges:
New-SPUser -UserAlias "companyABC.com\JohnS" -Web "http://portal.comapanyABC.com"
PowerShell also gives you the
ability to implement a similar procedure for disabling employee access
to a particular site and removing it from Active Directory, The
following example shows how to disable and remove a user:
# Removes a User from a SharePoint Site
Remove-SPUser –Web "http://portal.companyABC.com" -UserAlias "companyABC.com\JohnS"
# Disables AD User
Set-ADUser "JohnS" –Enabled $false
# Removes AD User
Remove-ADUser "JohnS" –confirm $false
If you have multiple site collections, you can combine Remove-SPUser with results from Get-SPSite | Get-SPWeb cmdlets.