One of the requirements we have in our project is to delete the web part from a page. So one of the obvious options is to delete the web part using a PowerShell script.
So here I will again step-by-step discuss how to do this using a PowerShell script.
Here we are using “MyCustomWP”as the name of the web part to delete, available in ZoneId 1 and order 1.
- Create the web instance and get the publishing web as follows:
- $webURL = “http:
- $web = Get-SPWeb $webURL
- [Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);
- Get the default value for the AllowUnsafeUpdates property to change it at the end and now set it to true:
- $allowunsafeupdates = $web.AllowUnsafeUpdates
- $web.AllowUnsafeUpdates = $true
- Get the Pages library and get the page from where we want to delete the web part:
- $list = $web.Lists[$pagesLibrary]
- if($list){
- $page = $web.GetFile(”My Page URL from where I want to delete the web part”)
-
- }
- If the page is not checked out to another user, then checkout the page, get the webpartmanager for the page and get all webparts available on the page.
- $page.CheckOut()
- $webpartmanager = $web.GetLimitedWebPartManager($page.URL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
- $WebPartCollection = $webpartmanager.WebParts
- Go through all the web part collections and compare them with our webpart name, ZoneId and Order.
- $webPartsCount = $WebPartCollection.Count
-
- for($i=0;$i -lt $WebPartCollection.Count; $i++){
Here we are checking the RepresentedWebPartType.Name. For details click here.
- if($webpartmanager.Webparts[$i].RepresentedWebPartType.Name -eq $webPartName -or $webpartmanager.Webparts[$i].GetType().Name -eq $MyCustomWP){
- if($webpartmanager.Webparts[$i].ZoneId -eq 1){
- if($webpartmanager.Webparts[$i].PartOrder -eq 1){
- $SPWebPart = $web.GetWebPartCollection($page.url,[Microsoft.SharePoint.WebPartPages.Storage]::Shared)
- $webPartTobeDeleted = $webpartmanager.Webparts[$i] $SPWebPart.Delete($webPartTobeDeleted.StorageKey)
- Write-Output "Deleted" $webPartTobeDeleted.GetType().Name
- $web.Update()
- break
- }#if part order
- }#if webpart zone
- }#if webpart type
- }#foor loop - $i
- Finally check in the page and close all the instances.
Check to ensure the page is checked out by you and if so, check it in
- if ($page.CheckedOutBy.UserLogin -eq $web.CurrentUser.UserLogin)
- {
- $page.CheckIn("Page checked in automatically by PowerShell script")
- Write-Output $page.Title"("$page.Name") has been checked in"
- }
Approve the page.
- $page.Approve("Page approved automatically by PowerShell script")
-
- $web.AllowUnsafeUpdates = $allowunsafeupdates
- $pubWeb.Close()
- $web.Dispose()
Thanks!
Your suggestions, feedback and comments are always welcome!