Tuesday, November 20, 2012

Remove a WebPart from SharePoint Pages using Powershell

The following script is very useful in removing a webpart from SharePoint page.


if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$spWeb = Get-SPWeb $siteUrl -ErrorAction Stop

#Declare the absolute path to the SharePoint page
$pagePath = "/SitePages/Home.aspx"
$pageUrl = $siteUrl + $pagePath
write-host "Processing site: ", $siteUrl
write-host "Processing page: ", $pageUrl

#Initialise the Web part manager for the specified profile page.
$spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

#List all the Webparts in the specified page
foreach ($webpart in $spWebPartManager.WebParts)
{
    write-host $siteUrl +": Existing Web part - " + $webpart.Title + " : " + $webpart.ID
    break;
}
#Remove the Share Documents Web part from that page
foreach ($webpart in ($spWebPartManager.WebParts | Where-Object {$_.Title -eq "Shared Documents"}))
{
    write-host $siteUrl +": Existing Web part - " + $webpart.Title + " : " + $webpart.ID
    $webpart1 = $webpart
    break;
}
#Delete the existing webpart
$spWebPartManager.DeleteWebPart($spWebPartManager.WebParts[$webpart1.ID])
write-host "Deleted the existing Shared Document web part."

$spWeb.Dispose()

2 comments:

  1. Thank you for sharing such an informative article. I really hope I can see other interesting posts. Keep up the good work!


    Melbourne App Developer

    ReplyDelete