Change page layout Using CSOM With PowerShell For SharePoint Online / SharePoint 2013

In this article, you will learn how to change the page layout of a publishing page using CSOM with PowerShell for SharePoint online / SharePoint 2013 / SharePoint 2016 sites.

Steps Involved:

The following section explains you the flow for changing the page layout.

  • Add the references using the Add-Type command with necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll and Microsoft.SharePoint.Client.Publishing.dll.

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

  • Initialize client context object with the site URL.

$siteURL = ""

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  

  • If you are trying to access SharePoint Online site, then you need to setup the site credentials with credentials parameter and get it set to the client context. 

# Not required for on premise site - Start

$userId = ""

$pwd = Read-Host -Prompt "Enter password" -AsSecureString  

$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  

$ctx.credentials = $creds   

# Not required for on premise site - End

  • If you are trying to access the SharePoint on premise site, then the credentials parameter is not required to be set to the context. But you need to run the code on the respective SharePoint server.

  • Then check if the page already exists. 

  1. Get the page library using GetByTitle method from the list collection.

  2. Then initialize the query object and set the query using view xml method.

  3. Get the items using GetItems method.

  4. Load and execute the query.

  5. Then check the items count.

# page to be changed

$pageName = "TestPage1.aspx"

# Get the page to change the layout

$lists = $ctx.web.Lists