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.
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.
- Initialize client context object with the site URL.
- 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.
- 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.
- Get the page library using GetByTitle method from the list collection.
- Then initialize the query object and set the query using view xml method.
- Get the items using GetItems method.
- Load and execute the query.
- Then check the items count.
- Get the page layout library and filter out page layout item using the query object.
- Once the query is set, get the necessary page layout using GetItems method.
- Since, it returns the item collection, we will take the first item from the collection.
- Get the file from page object.
- Check if page already checked out by other users. If so, then undo check out for editing.
- If its not checked out, then checkout here.
The page will be updated with new page layout.