Removing Web Parts from SharePoint Pages using PowerShell

The organization I work for uses SharePoint has a Case Management system. They create a SharePoint Site using the same template for each of their cases. As a SharePoint developer, I run into challenges every time they require a change to the site template. I need to ensure all new sites will get the change, but also need to retroactively apply the change to all existing sites to ensure conformity. We currently have over 13, 000 sites grouped inside of 1,200 site collections. A couple of days ago, a decision was made to remove 3 web parts on a certain page of the sites. I decided to take on the challenge and script this change using my new best firned, PowerShell.

PowerShell Logo

 

Basically my script loops through all site collections, through each site, accesses the page where the web parts are located, and removes the web part from the page. Items in bold represent values that you would need to modify if you want to re-use my script for your custom need. The only tricky part, is that I had to add the web part’s ID, once found on the page, to an array and delete them later, because if we delete them inside the foreach loop, the collection will change, and the script won’t be able to continue looping and will crash.

 

function CleanWebPartPage()

{

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint.WebPartPages”)

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint.Publishing”)

 

$site = new-object Microsoft.SharePoint.SPSite -argumentList “url of my farm“;

$webApplication = $site.WebApplication;

 

foreach($spsite in $webApplication.Sites)

{

foreach($spweb in $spsite.RootWeb.Webs)

{

$url = $spweb.Url;

$WebPageUrl = “Pages/page.aspx” #Nik – Relative Url of the page on which I need to remove the web parts;

$wpNames = @(“WebpartName1“, “WebPartName2“, “WebPartNameN“);

 

$spWpManager = $spweb.GetLimitedWebPartManager($WebPageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);

$webparts = @() #Nik – Declare empty array that will contain the GUID of the web parts on the current page;

 

foreach($spwebpart in $spWpManager.Webparts)

{

foreach($wptitle in $wpNames)

{

if($spwebpart.Title -eq $wptitle)

{

$webparts = $webparts + $spwebpart.ID # Nik – We’ve found a web part to be deleted, add its ID to the array;

}

}

}

 

foreach($webpartId in $webparts) #Nik – Now that we have the GUID of all web parts to delete, loop through them and delete them one at a time;

{

$spWpManager.DeleteWebPart($spWpManager.Webparts[$webpartId])

}

write-host $spweb.Title “…Done”

$spweb.Update();

$spweb.Dispose();

}

if($spWpManager -ne $null)

{

$spWpManager.Dispose();

}

$spsite.Dspose();

}

Microsoft Premier Field Engineer – SharePoint

Leave a Comment

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

*
*