Background
I was continuing with my SharePoint journey. Today’s my topic was to create custom page based on a Custom Page Layout in our Site Collection. In this blog, I will provide self-described script and this script will create the page using our custom page layout. This script will create the pages in a publishing portal only. If you want to create page in other than publishing site then you need to change the script accordingly.
It is a very straight forward script. I have a publishing site and my custom Page Layout has been deployed on the Publishing site as following figure.
Now following script will create the page in provided web site.
Script:
- Add the PowerShell Snapin
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
- Get the required Site URL,
$SiteUrl = "https://MySiteCollectionURL"
- Get the required Web URL (here my web is the root web, so the web url is same as site url)
$WebUrl = "https://MyWebURL"
- Get my custom PageLayout,
$PageLayoutRelUrl = "/_catalogs/masterpage/Kirti_CustomPageLayout.aspx"
- Get the Page URL,
$PageName = "Kirti.aspx"
- Get the Title of the Page which is going to get created,
$PageTitle = "Kirti"
- Initialize the Site Object,
$Site = Get-SPSite($SiteUrl)
- Get the Publishing Site based on the SPSite,
$PubSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($Site)
- Get the SPWeb Object,
$Web = Get-SPWeb $WebUrl
- Initialize the Publishing Web based on the SPWeb,
$PubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
- Get all PageLayouts Installed on the Publishing Site,
$Layouts = $PubSite.GetPageLayouts($False)
- Get my custom PageLayout,
$PageLayout = $Layouts[$PageLayoutRelUrl]
- Create a new publishing page using my custom page layout.
$Page = $PubWeb.AddPublishingPage($PageName, $PageLayout)
- Assign the Title to newly created Page,
$Page.Title = $PageTitle
- Update the Page,
$Page.Update();
- Check in the Page with Comments,
$Page.CheckIn("Kirti Page created")
- Publish the Page with Comments
$Page.ListItem.File.Publish("Kirti page Published ")
After running the script, my required page created in the site as shown in following figure.