In this article, you will learn how to add web part to a publishing page using CSOM with PowerShell on SharePoint 2013 / SharePoint 2016 / SharePoint online.
The following section explains the flow for adding web part to a publishing page.
- 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.
- Get the page from the respective library using server relative url. Load the file and execute the query to access the page components.
- Check if web part already exists. From the page, we will get the web parts present.
- From the file object, using web part manager and personalization scope we can access the page web parts.
- Load and execute the query to access the web parts.
- Load the individual web parts by loading the web part property
- Then compare and check all the web part titles with new web part using for each loop.
- Check the file is checked out by some one. If so, undo check out.
- If its not checked out, then check out the file using check out type "none" and check out method.
I have added a content editor web part to the page. Like wise any other web part can be added to the page using the respective web part file. Here generating or using the correct web part file is important. Apart from that, there will not be any change in addition logic explained.