How to set a custom master page to the site in SharePoint 2010


In this article we will be seeing how to set the custom master page to the site in SharePoint 2010 using powershell and using console application.

In this article, I have created custom master page and it is placed in the physical path. Through script I will be uploading the master page to "Master Page Gallery" and set the master page to the SharePoint site.

Set a master page to the site in SharePoint 2010 using powershell script

# -------------Comments

$publishComment="Published"
$approveComment="Approved"
$checkInComment="Custom Master Page added"



$site=Get-SpSite "http://servername:1111/"
$web=$site.RootWeb
$masterPageLocalDir = "C:\CustomMasterPage.master"
$masterPageFolder = $web.GetFolder("Master Page Gallery")

# -------------Uploading the master page to the "Master Page Gallery"

Get-ChildItem $masterPageLocalDir | foreach {
$stream = [IO.File]::OpenRead($_.FullName)
$desturl = $web.Url+"/_catalogs/masterpage/"+$_.Name.Replace(" ","")
$resultingfile =$masterPageFolder.files.Add($desturl,$stream,$true)
$stream.close()

}

# -------------Check In, Publish and Approve

$masterPageFile=$web.GetFile($desturl)
$masterPageFile.CheckIn($checkInComment);
$masterPageFile.Publish($publishComment);
$masterPageFile.Approve($approveComment);
$masterPageFile.Update();



# -------------Set the master page to the site

$masterUri=New-Object System.Uri($desturl)
$web.MasterUrl=$masterUri.AbsolutePath
$web.CustomMasterUrl=$masterUri.AbsolutePath
$web.Update()
$web.Dispose()
$site.Dispose()


For creating master page using visual studio 2010 refer http://www.c-sharpcorner.com/UploadFile/anavijai/5224/