Pages

Friday, November 30, 2012

Set Masterpage Poweshell SharePoint



PowerShell commands come handy when you have to perform administrative tasks in your SharePoint environment. In past where you have to write code or a small utility program like a console application or Windows Form application can now be achieved using PowerShell script. . I use this a lot with my clients and since PowerShell script is run by the administrators the IT people love it and don’t have to worry about anything.
In the recent times I have been asked by my clients to provide them with a script to set master pages across multiple site collection in a web application in order to push their branding. I thought that the same script will be useful for a lot of people like me and decided to share the script here by making the script more generic than the one I wrote for my clients.
#Enter the site URL
$siteUrl = Read-Host "Enter Site URL"
$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)
$spWebApp = $rootSite.WebApplication
foreach($site in $spWebApp.Sites)
{
$web = Get-SPWeb $site.Url
$featureFolderNameSite = "PublishingSite"
$featureFolderNameWeb = "PublishingWeb"
$FeatureIDSite = Get-SPFeature -Site $web.Url | Where {$_.DisplayName -eq $featureFolderNameSite}
$FeatureIDWeb = Get-SPFeature -Web $web.Url | Where {$_.DisplayName -eq $featureFolderNameWeb}
# Check Publishing feature is active at site level and site collection level
#if not active activate.
if($FeatureIDSite -ne $null)
{
   Write-Host $featureFolderNameSite "is already activated at :" $web.Url
}

else
{
    Enable-SPFeature -Identity $featureFolderNameSite -Confirm:$false -Url $web.Url
    Write-Host $featureFolderNameSite "has been activated at :" $web.Url
}

if($FeatureIDWeb -ne $null)
{
    Write-Host $featureFolderNameWeb "is already activated at :" $web.Url
 }

else
{
    Enable-SPFeature -Identity $featureFolderNameWeb -Confirm:$false -Url $web.Url
    Write-Host $featureFolderNameSite "has been activated at :" $web.Url
}
$web.CustomMasterUrl = "/_catalogs/masterpage/nightandday.master"
$web.MasterUrl = "/_catalogs/masterpage/nightandday.master"
$web.Update()
$site.Dispose()
}
$rootSite.Dispose()

The script takes the Site URL from the user and loops through all the available site collection present in the web application in which the current site collection is part and sets the master page on all the site collections. The script also activates publishing feature at the site collection level and at site level before setting the master page if it is not activates already.