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.


$wpName = "Your_Web_Part_Name";
$checkedOut = @()
$site = new-object Microsoft.SharePoint.SPSite -argumentList "";

$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)
		$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)
	write-output "$url has been processed."
	write-output "The following pages were checked out and could not be processed: $checkedOut"


	if($spWpManager -ne $null)

The code file can be found here.

See you,



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?


    • 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.


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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: