Removing a Web Part from Pages Using Powershell


Hi all!

Today I’m just posting this useful Powershell script to remove a web part from all the pages in a specific site.

It goes through all the libraries you define and looks for instances of the web part and removes to ones it finds.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WebPartPages")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")

$wpName = "Your_Web_Part_Name";
$checkedOut = @()
$site = new-object Microsoft.SharePoint.SPSite -argumentList "http://yourwebapplicationurl.com";

$webApplication = $site.WebApplication;

foreach($spsite in $webApplication.Sites)
{
	$spweb = $spsite.OpenWeb("your web site name")
	$url = $spweb.Url;

	write-output "Processing $url"

	# libraries to check for the web part on pages
	$libraries = @("Pages");

	foreach($lib in $libraries)
	{
		$list=$spweb.Lists[$lib]
		$title = $list.Title
		foreach($item in $list.Items)
		{
			$WebPageUrl = $item.Url
			write-output "Processing page $WebPageUrl"

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

			if ($item.File.CheckOutType -ne "None")
			{
				$checkedOut = $checkedOut + $WebPageUrl + ","
			}

			foreach($spwebpart in $spWpManager.Webparts)
			{
				if($spwebpart.Title -eq $wpName)
				{
					$webparts = $webparts + $spwebpart.ID
				}
			}

			foreach($webpartId in $webparts)
			{
				$spWpManager.DeleteWebPart($spWpManager.Webparts[$webpartId])
			}
		}
	}
	write-output "$url has been processed."
	write-output "The following pages were checked out and could not be processed: $checkedOut"

	$spweb.Update();
	$spweb.Dispose();

	if($spWpManager -ne $null)
	{
		$spWpManager.Dispose();
	}
	$spsite.Dispose();
}

The code file can be found here.

See you,

Amadeu.

Advertisements

2 Responses to Removing a Web Part from Pages Using Powershell

  1. Stephan Onisick says:

    Doesn’t this assume your web part is in the Pages library. What about a web part page in a regular document library?

    thanks,
    Stephan

    • ascampanelli says:

      Hi Stephan.
      Yes, the script assumes the pages are on the Pages library.
      You can tweak it changing the array $libraries to point to more document libraries.
      Please try this on line 18:
      $libraries = @(“Pages”, “DocLib2”, “DocLib3”);

      I hope this helps.

      Amadeu.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: