PowerShell Script to Create Publishing Page using Custom PageLayout in SharePoint 2013

Introduction

In this blog we will about create a custom page in SharePoint 2013 using PowerShell method. We need to create many pages based on a Custom Page Layout in our Site Collection for our development purpose.

For that I have created a small PowerShell script to work on this.

Steps

  1. Start your windows PowerShell on your computer.
  2. Right click and select Run as administrator option.
  3. Paste the below script on the PowerShell window and click the enter button.
  4. Check your SharePoint site page will be created successfully.
  1. # Add the PowerShell Snapin  
  2.   
  3.  $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}  
  4.   
  5.  if ($snapin -eq $null)   
  6.  {   
  7.      Add-PSSnapin "Microsoft.SharePoint.Powershell"  
  8.  }  
  9.    
  10.  # Get the SiteURL  
  11.  $SiteUrl = "https://Thegowtham.sharepoint.com"  
  12.    
  13.  # Get the WebURL  
  14.  $WebUrl = "https://the gowtham.sharepoint.com/sites/TS"  
  15.    
  16.  # Get the PageLayout  
  17.  $PageLayoutRelUrl = "/_catalogs/masterpage/CustomPageLayout.aspx"  
  18.    
  19.  # Get the Page URL  
  20.  $PageName = "TestSite.aspx"  
  21.    
  22.  # Get the Title of the Page which is going to get created  
  23.  $PageTitle = "SamplePage"  
  24.    
  25.  # Initialize the Site Object  
  26.  $Site = Get-SPSite($SiteUrl)  
  27.    
  28.  # Get the Publishing Site based on the SPSite  
  29.  $PublishingSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($Site)  
  30.    
  31.  # Get the SPWeb Object  
  32.  $Web = Get-SPWeb $WebUrl  
  33.    
  34.  # Initialize the PublishingWeb based on the SPWeb  
  35.  $PublishingWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)  
  36.     
  37.  # Get the PageLayouts Installed on the Publishing Site  
  38.  $Layouts = $ PublishingSite.GetPageLayouts($False)  
  39.    
  40.  # Get our PageLayout  
  41.  $PageLayout = $Layouts[$PageLayoutRelUrl]  
  42.     
  43.  # Create a new publishing page.  
  44.  $Page = $ PublishingWeb.AddPublishingPage($PageName, $PageLayout)  
  45.    
  46.  # Assign the Title for the Page  
  47.  $Page.Title = $PageTitle  
  48.    
  49.  # Update the Page  
  50.  $Page.Update();  
  51.    
  52.  # Check in the Page with Comments  
  53.  $Page.CheckIn("Page Created Successfully")  
  54.    
  55.  # Publish the Page With Comments  
  56.  $Page.ListItem.File.Publish("Page Created Successfully and  Publish Comment")  
Run the script with the required administrator privilege.

To verify that, go the Pages Library and make sure that new page available or not.