Friday 13 May 2016

Add webpart to page Using CSOM With PowerShell on SharePoint


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.


Steps Involved:


The following section explains the flow for adding web part to a publishing page.
  1. 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.
    1. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"  
    2. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
    3. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"  
  2. Initialize client context object with the site URL.
    1. $siteURL = ""  
    2. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  3. 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. 
    1. #Not required for on premise site - Start  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx.credentials = $creds   
    6. #Not required for on premise site - End  
  4. 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.
  5. Get the page from the respective library using server relative url. Load the file and execute the query to access the page components.
    1. #page where web part to be changed  
    2. $pageName = "TestPage1.aspx"  
    3. #Get the page to add  
    4. $file = $ctx.Web.GetFileByServerRelativeUrl("/Pages/TestPage1.aspx")  
    5. $ctx.Load($file)  
    6. $ctx.ExecuteQuery()  
  6. 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.
      1. #Get all the webparts  
      2. Write-Host "Retrieving webparts"  
      3. $wpManager = $file.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)  
      4. $webparts = $wpManager.Webparts  
      5. $ctx.Load($webparts)  
      6. $ctx.ExecuteQuery()  
      7.   
      8. $webparts | ForEach-Object { $ctx.Load($_.WebPart) }  
      9. $ctx.ExecuteQuery()  
      10.  
      11. #New web part name  
      12. $newwpTitle = "Content Editor"  
      13. #Web part exists flag  
      14. $wpExists = $false  
      15. if($webparts.Count -gt 0){  
      16.     Write-Host "Looping through all webparts"  
      17.     foreach($webpart in $webparts){  
      18.         if($webpart.WebPart.Title -eq $newwpTitle){  
      19.             Write-Host "Webpart present"  
      20.             $wpExists = $true  
      21.         }  
      22.               
      23.     }  
      24. }  
      25. if(!$wpExists){  
      26.     #your further code goes here.  
      27. }  
  7. If web part not present, then we will add the web part. Check out the file using below logic.
    • 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.
      1. #Check if page already checked out. If so, undo check out  
      2. if($file.CheckOutType -eq [Microsoft.SharePoint.Client.CheckOutType]::Online){  
      3.     try{  
      4.         Write-Host "Undo Checkout"  
      5.         $file.UndoCheckOut()  
      6.         $ctx.load($file)  
      7.         $ctx.ExecuteQuery()              
      8.     }  
      9.     catch{  
      10.         write-host "Error in checkout.. $($_.Exception.Message)" -foregroundcolor red  
      11.     }  
      12. }  
      13.  
      14. #If page is not checked out, then check out  
      15. if($file.CheckOutType -eq [Microsoft.SharePoint.Client.CheckOutType]::None){  
      16.     Write-Host "Checkout"  
      17.     $file.CheckOut()  
      18.     $ctx.Load($file)  
      19.     $ctx.ExecuteQuery()  
      20. }  
  8. Then access the web part file. It will have extension of webpart or dwp. It is a xml file with necessary web part details like title, zone id, header, etc. The web part xml can be generated by exporting and modifying the existing web part files. Once generated, import the web part xml and add it to web part manager with necessary zone id and zone index.
    1. Write-Host "Adding webpart"  
    2. $XmlDocument = Get-Content -Path "local drive path/NewWebpart.xml"  
    3. $importWP = $wpManager.ImportWebPart($XmlDocument)  
    4. $wpManager.AddWebPart($importWP.WebPart,0,0)  
    5. $ctx.ExecuteQuery()  
  9. Then check in and publish the page.
    1. Write-Host "Page checkin"  
    2. $file.CheckIn("Added webpart", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)  
    3. $ctx.load($file)  
    4. $ctx.ExecuteQuery()  
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.