Removing Webparts from SharePoint Site Pages with Powershell

The following PowerShell snippet shows how to remove a WebPart from a page in SharePoint by it’s title. I wrote it up because it’s not as straightforward as you might imagine – you need to loop through the WebParts in the page via the “webpartmanager” object – there is no enumeration of WebParts in a page.

$webpart_title = "Hello World"
$page_filename = "home.aspx"

# Connect to Web
$web = Get-SPWeb "https://intranet.contoso.com"

# Instantiate Webpart Manager
$webpartmanager = $web.GetLimitedWebPartManager($($web.Url + "/SitePages/" + $page_filename),[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$webpartsarray = @()

for($i=0;$i -lt $webpartmanager.WebParts.Count;$i++) {
  if($webpartmanager.WebParts[$i].title -eq $webpart_title) {
    $webpartsarray = $webpartsarray + $webpartmanager.WebParts[$i].ID
  }
}

$num_webparts = $webpartsarray.length

if ($num_webparts -gt 0)
{
  Write-Host "Found Webpart [$webpart_title]"
  for($j=0; $j -lt $num_webparts; $j++)
  {
    Write-Host $("Deleting WebPart [" + $webpartsarray[$j] + "]")
    $webpartmanager.DeleteWebPart($webpartmanager.WebParts[$webpartsarray[$j]])
  }
}
else
{
  Write-Host "WebPart Not found"
}

# release resources
$web.Close()
$web.Dispose()

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.