Tuesday, November 5, 2013

Alter Content Editor Webpart Content using PowerShell

I wanted a way to programmatically alter few URLs added as the content of a CEWP. Basically I was creating couple of site collections using the same site template and wanted to update Content Editor webpart content during the deployment. For the purpose I used a PowerShell script like:

function FixCEWebPartContent([string] $targetWebUrl,[string]$targetPage, [string]$oldPath, [string]$newPath){        
  write-host "Processing Page $targetPage in web $targetWebUrl"
  $web = Get-SPWeb($targetWebUrl)
  $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
  $pages = $pWeb.GetPublishingPages()     
  $page = $pages | where {$_.name -eq $targetPage } 
  $page.Checkout()  
  $targetPageURL = "pages/"+$targetPage
  $wpm = $web.GetLimitedWebPartManager($targetPageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
  foreach($webpart in $wpm.WebParts){
    if($webPart.GetType() -eq [Microsoft.SharePoint.WebPartPages.ContentEditorWebPart]){
      write-host "Webpart found: $webpart.Title"               
      $oldWPContent = $webPart.Content;
      $oldContentText = $oldWPContent.InnerText;

      $xmlDoc = New-Object xml;
      $newXmlElement = $xmlDoc.CreateElement("Content");
      $newXmlElement.InnerText = $oldContentText.Replace($oldPath, $newPath);
      $webPart.Content = $newXmlElement;
      $wpm.SaveChanges($webPart);
      write-host "Web part updated"  
    }               
  }
  $page.CheckIn("")
  $file = $page.ListItem.File
  $file.Publish("")
  $web.Dispose()    
}
This script iterates through all the webparts in a given page and filter content editor webparts based on the webpart type. Alternatively we can filter the webparts based on its title, if we know the content editor webpart title.

if($webpart.Title -eq "My Content Editor Webpart")
When a content editor webpart is found, current content is copied to a local variable and altered with the string.Replace function. Then a XML element is created using the updated content and set back to the webpart.

Above function can be invoked as:

FixCEWebPartContent -targetWebUrl "http://prasad/path-1" -targetPage "Home.aspx" -oldPath "/path-1/_catalogs/"-newPath "/path-2/_catalogs/"

No comments: