Remove all webparts

For a recent SP2010 to SP2013 upgrade, we have a SharePoint Publishing page that has some SandBoxed Solution webparts.   We need to REMOVE these webparts – as we’re going with a different approach – some JavaScript/CSOM – to do the same function.

Anyway, I’ve defined a script that will get a SP page, and remove ALL webparts.

This is via PowerShell + CSOM, so the same approach would would work for SP2013, or O365 (just need a different ClientContext – and login/connection).

# values from constants
$urlSite = "https://intranet/projectX"

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($urlSite)
$ctxWeb = $ctx.Web
[Microsoft.SharePoint.Client.Publishing.PublishingWeb] $pubWeb = [Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($ctx, $ctxWeb);

function RemoveAllWebParts($pageName)
    $messageText = "Checking page " + $pageName

	# remove webparts 
	# wipe them out - ALL of them      (order 66)

	# get the pages library		
	$pagesLib = $ctxWeb.Lists.GetByTitle("Pages");
	# find the page we wanna ditch the webparts from
    [Microsoft.SharePoint.Client.CamlQuery] $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
	$camlQuery.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + $pageName + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></Query></View>"
	$pageFound = $false
	$pageItems = $pagesLib.GetItems($camlQuery)

	if($pageItems.Count -gt 0)
	{	$pageFound = $true
		$pubPageItem = $pageItems[0]
		$pubFile = $pubPageItem.File
	if($pubFile.CheckOutType -eq [Microsoft.SharePoint.Client.CheckOutType]::None -or $pubFile.CheckOutType -eq $null)

	$wpm = $pubFile.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared);
    $webparts = @();

	$wpcoll = $wpm.WebParts;

    $messageText = "Delete webparts for the page";

    foreach($spwebpart in $wpcoll)
        $webparts = $webparts + $spwebpart.ID;

	if($pubFile.CheckOutType -ne [Microsoft.SharePoint.Client.CheckOutType]::None)
		$pubFile.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn);

RemoveAllWebParts 'Page1.aspx';
RemoveAllWebParts 'Page2.aspx';
RemoveAllWebParts 'Page3.aspx';
RemoveAllWebParts 'Page4.aspx';

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s