Set Content Editor Web Part (CEWP) Content with PowerShell

Scenario:
We have a Project site collection with 100’s of sub sites created for each project from a custom site template. The home page of each site has a content editor web part with some content in it, titled “Dashboard Links”. Years later, The business wanted to change the content in the “Dashboard Links” on each site!

So, Here the requirement is to set the Content Editor web part’s content in all sub sites. Lets use PowerShell to automate:

Set Content Editor Web Part (CEWP) Content with PowerShell

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Site collection
$site=Get-SPSite "https://sharepoint.crescent.com/PMO/"

#Loop throgh each subsite in the site collection
foreach($web in $Site.AllWebs)
{
  #Get the Default.aspx file
  $file= $web.GetFile($web.Url +"/SitePages/Home.aspx")

  if($file.Exists)
    {
     #Web Part Manager to get all web parts from the file
     $WebPartManager = $web.GetLimitedWebPartManager( $file,  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
 
     #Iterate through each web part
     foreach($webPart in $WebPartManager.WebParts) 
      {
        # Get the Content Editor web part with specific Title
        if( ($webPart.title -eq "Dashboard Links") -and ($webPart.GetType() -eq [Microsoft.SharePoint.WebPartPages.ContentEditorWebPart]) )
        {
           #Content to be Placed inside CEWP
           $HtmlContent= "<ul><li><a href='/pmo/dashboard/team-allocation.aspx'>PMO Team Allocation</a></li><li><a href='/pmo/dashboard/bi-dashboard.aspx'>PMO Business Intelligence Dashboard</a></li><li><a href='/pmo/dashboard/pmi-admin.aspx'>PMO PMIS Admin</a></li><li><a href='/pmo/dashboard/pmo-yammer.aspx'>PMO on Yammer</a></li></ul>"

           $XmlDoc = New-Object System.Xml.XmlDocument
     $contentXml=$xmlDoc.CreateElement("content") 
           $contentXml.InnerText= $HtmlContent

           #Set content and Save
           $webpart.Content = $contentXml     
           $webPartManager.SaveChanges($webPart);
         }
      }
    }
 }

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *