ENTERPRISE

SharePoint 2010 : Cataloging the Best Scripts to Automate SharePoint Administration

2/8/2011 9:03:51 AM

Automating Creation of Web Applications and Site Collections

Administrators benefit from PowerShell when they need to create a number of site collections. This can often happen when administrating large SharePoint farms or providing hosting services.

Site collection creation operations consist of three steps:

1.
Create an IIS web application and application pool.

2.
Create a site collection.

3.
Choose a template for the site collection.

These operations can be performed via central administration or easily automated via PowerShell. The following example combines all three steps as a single cmdlet:

Function New-SPSiteSet
{
param(
[Parameter(Mandatory=$true)]
[string]$SiteName,
[int]$Port = 80,
[string]$HostHeader = "",
[string]$URL = "",
[Parameter(Mandatory=$true)]
[string]$ApplicationPool,
[Parameter(Mandatory=$true)]
[string]$ApplicationPoolAccount,
[string]$SiteCollectionOwner = $ApplicationPoolAccount,
[string]$TemplateName = "Blank Site"
)

if($URL -ne "")
{
New-SPWebApplication -Name $SiteName -Port $Port -HostHeader $HostHeader -URL $Url -ApplicationPool $ApplicationPool -ApplicationPoolAccount (Get-SPManagedAccount $ApplicationPoolAccount)
}
else
{
New-SPWebApplication -Name $SiteName -Port $Port -HostHeader $HostHeader -ApplicationPool $ApplicationPool -ApplicationPoolAccount (Get-SPManagedAccount $ApplicationPoolAccount)
}

$webApplication = Get-SPWebApplication $SiteName
$currentUserAlias = "{0}\{1}" -f $Env:USERDOMAIN, $Env:USERNAME
$templates = Get-SPWebTemplate | Where {$_.Name -eq $TemplateName -or $_.Title -eq $TemplateName}
if($templates.Length -eq $null)
{
$template = $templates.Name
}
else
{
$template = $templates[0].Name
}

if($template -eq $null)
{
$templates = Get-SPWebTemplate | where {$_.IsHidden -eq $false -and $_.IsRootWebOnly -eq $false}
$template = $templates[0].Name
}


New-SPSite -Name "SiteName" -Url $webApplication.Url -OwnerAlias $SiteCollectionOwner -SecondaryOwnerAlias $currentUserAlias
Get-SPWeb $webApplication.Url | Set-SPWeb -Template $template

}


To execute this function, type the following into the PowerShell shell:

New-SPSiteSet -SiteName "NewSiteCollection" -Port 8080 -ApplicationPool "ApplicationPool-NewSiteCollection" -ApplicationPoolAccount "companyABC.com\SPServiceAccount"

The script calls all necessary cmdlets and enables you to create a new site collection with a single call. In the previous example, a site collection with the associated pool will be created, and it will be available at port 8080 with the default template (Blank site).

The function can be further customized with additional site collection parameters as needed. Default parameters include

  • SiteName— Name for your site collection and web application.

  • Port— Port that will be used for your site collection URL; default port is 80.

  • HostHeader— Optional host header, for example, portal.companyABC.com. If the host header is not provided, site collection will be available as http://SP_Server_Name:Port.

  • URL— Custom URL for your site collection.

  • ApplicationPool— Name of application pool that will be used.

  • ApplicationPoolAccount— Account that will be used as application pool account (must be managed account).

  • SiteCollectionOwner— Account that will be primary site collection administrator. If value is not provided, ApplicationPoolAccount will be used instead.

  • TemplateName— Template that will be applied to newly created site collection. If value is not provided, "Blank Site" will be used.

Creating Site Structures On-the-Fly

SharePoint comes with many built-in templates that you can customize to match your needs. With PowerShell, you can streamline site creation for any purpose you need. You can leverage the built-in cmdlets to create and tear up site structures.

The following sample shows how PowerShell can be used to help you automate creation of a site structure. It combines the ability to list templates and create a new site. The script first lists all available site templates. (Hidden and templates designed for root sites only are not listed.) For each site in that collection, a site will be created.

Here is the sample:

Function Create-SPMockupSites($Path)
{
$webTemplates = Get-SPWebTemplate | where {$_.IsHidden -eq $false -and $_.IsRootWebOnly -eq $false -and $_.Name -ne "BICenterSite#0"}$
New-SPWeb -url ($Path + "/templates") -Template "STS#1" -Name "Templates"
$rootWeb = Get-SPWeb ($Path + "/templates")

ForEach($webTemplate in $webTemplates)
{
$webTemplate.Title
New-SPWeb -url ($rootWeb.Url + "/" + $webTemplate.Title) -Template $webTemplate.Name -Name $webTemplate.Title -Description $webTemplate.Description
}
}

To use the preceding code, type the following:
Create-SPMockupSites("http://portal.companyABC.com")

The script creates a blank site at http://portal.companyABC.com/Templates, and then a subsite below it for each template available.

In out-of-the-box SharePoint installation, this command creates approximately 20 new sites. Use this script when you are preparing presentations, building demo sites, or preparing educational sites for end users.

Administrators can create a similar sample when you need to create a number of sandbox sites for an upcoming educational course. All these sites could use the same template but have a different site owner.

Automating Site Collection Backups with PowerShell

A script for automating site collection backups via STSADM commands was included in the previous version of this book. This script was one of the most asked-for scripts from the book because it enabled administrators to back up individual site collections to flat files on a nightly basis. Although useful, this script was a four-page Visual Basic script and had some complex logic in it that would enumerate site collections and back them up individually.

SharePoint 2010 now allows for the same functionality, from a simplified interface. You can completely automate the backup procedure with built-in SharePoint PowerShell cmdlets. The following sample script demonstrates some additional things than can be done with a combination of a couple of built-in scripts.

The script enables you to do the following:

  • Back up all site collections in your server farm.

  • The backup filename will be a combination of the site collection name and date when the backup was created.

  • The user running this script can specify the number of previous backups they want to retain.

  • When the backup finishes, a notification will be sent to a specified email address.

Here is the script listing:

Function Backup-SPSiteCollections ()
{
param(
[Parameter(
Position=0,
Mandatory=$true
)]
[Guid]$SPSiteID,
[Parameter(
Position=0,
Mandatory=$true
)]
[string]$BackupFolder,
[Parameter(
Position=0,
Mandatory=$true
)]
[string]$RootWeb,
[Parameter(
Position=0,
Mandatory=$true
)]
[int]$BackupFilesLimit,
[Parameter(
Position=0,
Mandatory=$false
)]
[string]$Email = "",
[Parameter(
Position=0,
Mandatory=$false
)]
[string]$SmtpServer = ""
)

# Test if backup folder exists
if (Test-Path $BackupFolder)
{
# Retrieve previous backup files , sorted by last write time (last modified)
$files = Get-Childitem $BackupFolder | where {$_.Name -like ("*" + $RootWeb + "*.dat")} | Sort $_.LastWriteTime
$filesCount = @($files).Count

# If there are more files in directory than backupFilesLimit
if($filesCount -ge $BackupFilesLimit)
{
# Delete all older files
for ( $i=0; $i -lt $filesCount-$BackupFilesLimit+1; $i++)
{
Remove-Item ($BackupFolder + $files[$i].Name)
}
}
}
# If backup folder does not exist it will be created
else
{
New-Item $BackupFolder -type directory
}
$backupFileName = ("" + $RootWeb + "_" + (Get-Date -Format yyyy-MM-ddThh-mm-ss) + ".dat")
$backupFilePath = $BackupFolder + $backupFileName
$startTime = Get-Date
Backup-SPSite -identity $_.ID -path ($backupFilePath) -force
$endTime = Get-Date

# Checking if Email and SmtpServer values have been defined
if($Email -ne "" -and $SmtpServer -ne "")
{
$subject = "SharePoint Site Collection Backup Completed!"
$body = "The following site collection was backed up: " + $RootWeb + "`n"
$body += "Site collection was backed up to: " + $backupFileName + "`n"
$body += "Backup started on: " + $startTime + ", and ended on: " + $endTime + "`n`n"
# Retrieving Site Collection size
$SiteCollectionSize = Get-SPSite | Where {$_.ID -eq $SPSiteID} | Select @{Expression={$_.Usage.Storage/1MB}}
# Retrieving backup file size
$backupFileSize = Get-ChildItem $backupFilePath | Select {$_.Length/1MB}
$body += "Site collection size on SharePoint system is: " + $SiteCollectionSize + " MB`n"
$body += "Backup file size: " + $backupFileSize + " MB"
$smtp = new-object Net.Mail.SmtpClient($SmtpServer)
# Sending email
$smtp.Send($Email, $Email, $subject, $body)
}
}

You can execute this script by using the following code snippets:
# Backup all site collections in your farm
Get-SPSite | ForEach-Object {Backup-SPSiteCollections -SPSiteID $_.ID -BackupFolder
"C:\Backup-Location\" -RootWeb $_.RootWeb -BackupFilesLimit 5 -Email
"administrator@companyABC.com" -SmtpServer "mail.companyABC.com"}
#Backup a site collection whose URL equals http://portal.companyABC.com
Get-SPSite | Where {$_.ID -eq "http://portal.companyABC.com"} | ForEach-Object
{Backup-SPSiteCollections -SPSiteID $_.ID -BackupFolder "C:\Backup-Location\"
-RootWeb $_.RootWeb -BackupFilesLimit 5 -Email "administrator@companyABC.com" -
SmtpServer "mail.companyABC.com"}
#Backup all site collections whose URL is not equal to http://no-
backup.companyABC.com, no emails will be sent
Get-SPSite | where {$_.ID -ne "http://no-backup.companyABC.com"} | ForEach-Object
{Backup-SPSiteCollections -SPSiteID $_.ID -BackupFolder "C:\Backup-Location\" -
RootWeb $_.RootWeb -BackupFilesLimit 5}


The preceding three samples show you how you can execute your script in various scenarios. A backup script has six parameters:

  • SPSiteID— GUID that uniquely identifies a site collection. In the previous samples, we pass the ID value from the ForEach-Object loop.

  • BackupFolder— Backup folder on a local drive. Leave the trailing backslash \. In case this folder does not exist, it will be automatically created.

  • RootWeb— Value of site collection RootWeb property. The value being used forms the backup filename—for example, RootWeb-BackupTime.dat.

  • BackupFilesLimit— The number of previous backup files to retain at BackupFolder location. In case this number is five, only five last backups will be left in the backup folder, and all previous files will be deleted.

  • Email— The email value used as a To and From email address. This value is optional. If value is not provided, a notification email will not be sent.

  • SmtpServer— The address of the SMTP server to send the notification email to. If this value is not provided, an email will not be sent.

Automatic Solution Installation

Sometime when administrators need to prepare a new SharePoint environment, a number of features need to be installed and deployed. New solutions cannot be added from the user interface, only with STSADM or PowerShell. Third-party solutions usually have a built-in installer, but most free solutions or in-house solutions do not come with one. To install and deploy these features, you need to run a few cmdlets. The following script is going to ease that procedure for you.

The following sample “connects” a number or built-in cmdlets and creates a single function that streamlines the installation process. The script is listed here:

Function Install-SPFeatures ($Path)
{
$files = get-childitem $Path | where {$_.Name -like "*.wsp"}

ForEach($file in $files)
{
$existingSolution = Get-SPSolution | Where{$_.Name -eq $file.Name}
# check if this soltion already exists
if($existingSolution -eq $null)
{
Add-SPSolution -LiteralPath ($Path + "\" + $file.Name)
}
# upgrade existing solution
else
{
# if solution is deployed we will update it with new version
if($existingSolution.Deployed -eq $true)
{
Update-SPSolution -identity $existingSolution.SolutionId -LiteralPath ($Path + "\" + $file.Name) -GACDeployment
}
# non-deployed solution need to be removed and installed
else
{
Remove-SPSolution -identity $existingSolution.SolutionId -confirm:$false
Add-SPSolution -LiteralPath ($Path + "\" + $file.Name)
}
}

$existingSolution = Get-SPSolution | Where {$_.Name -eq $file.Name}
if($existingSolution -ne $null)
{
Install-SPSolution -identity $existingSolution.SolutionId -GACDeployment -force
}

}


}

To execute this script, call it with
Install-SPFeatures "C:\Installation-Store\"

Installation-Store in the preceding example is the folder on your local drive (or network drive) that contains a number of WSPs. The script will iterate trough WSP files in this folder and try to add and deploy each solution.

There are some limitations in the script. If there is a solution with the same name, it will be upgraded. During deployment, GAC deployments are allowed so use these scripts only with trusted solutions. Solutions will be deployed to all sites.

Other  
  •  SharePoint Administration with PowerShell (part 2)
  •  SharePoint Administration with PowerShell (part 1)
  •  Sharepoint 2007: Approve or Reject a File or List Item
  •  Exchange Server 2007 : Configure the Client Access Server - Enable POP3 and IMAP4
  •  Exchange Server 2007 : Configure the Client Access Server - Enable and Configure Outlook Anywhere
  •  Exchange Server 2007 : Configure the Client Access Server - Create and Apply ActiveSync Mailbox Policies
  •  SharePoint 2010 : Understanding Windows PowerShell Concepts (part 3)
  •  SharePoint 2010 : Understanding Windows PowerShell Concepts (part 2)
  •  SharePoint 2010 : Understanding Windows PowerShell Concepts (part 1)
  •  Managing and Administering SharePoint 2010 Infrastructure : Using Additional Administration Tools for SharePoint
  •  Managing Exchange Server 2010 : Archiving and compliancy (part 3) - Discovery
  •  Managing Exchange Server 2010 : Archiving and compliancy (part 2) - Messaging Records Management
  •  Managing Exchange Server 2010 : Archiving and compliancy (part 1) - Exchange 2010 Archiving
  •  Managing Exchange Server 2010 : Role Based Access Control (RBAC)
  •  SharePoint 2007 : See What Files or List Items Are Checked Out to You
  •  SharePoint 2007 : Publish a File or List Item
  •  SharePoint 2007 : Use the Datasheet View to Add, Edit, or Delete Items and Files
  •  Exchange Server 2007 : Configure the Client Access Server - Manage Exchange ActiveSync
  •  Exchange Server 2007 : Configure the Client Access Server - Manage OWA
  •  Exchange Server 2007 : Configure the Client Access Server - Administer the CAS Role
  •  
    Top 10
    Microsoft .NET : Design Principles and Patterns - From Principles to Patterns (part 2)
    Microsoft .NET : Design Principles and Patterns - From Principles to Patterns (part 1)
    Brother MFC-J4510DW - An Innovative All-In-One A3 Printer
    Computer Planet I7 Extreme Gaming PC
    All We Need To Know About Green Computing (Part 4)
    All We Need To Know About Green Computing (Part 3)
    All We Need To Know About Green Computing (Part 2)
    All We Need To Know About Green Computing (Part 1)
    Master Black-White Copying
    On-Scene Portrait Photography Techniques
    Most View
    Managing SharePoint 2010 Data : Custom Field Types
    Installing Exchange Server 2010 : Installing dedicated server roles
    Programming with DirectX : Additional Texture Mapping - Sprites
    Troubleshooting Guide - Internet Connection Problems
    Windows Azure : Processing with worker roles - A simple worker role service
    Tech Preview 2013 (Part 1) - Next-Gen Gpus
    Group Test: Which Are The Best Cases On The Market? (Part 3) - Silverstone Fortress FT03 Elysium
    The Best Speaker Docks
    Remove Internet Limits With A VPN (Part 3)
    Toshiba Satellite P875 – Outstanding Desktop Replacement
    Tasmania - Ideal Destination For Landscape Photographers (Part 2)
    Intel In Flux: Are We Heading To A Socket-Less Future? (Part 1)
    Rig Builder – May 2012 (Part 5)
    Communicate over the Internet (WCF)
    Mobile Application Security : The Apple iPhone - Permissions and User Controls
    Windows Vista : Managing Your Contacts
    Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 1)
    Personalizing Windows 8 : Choosing Your Language
    Focal XS Book Music System
    3D TV Takes A Back Seat