I had come across a requirement where I had to automate the deletion of the webpart from the page and not from Webpart Gallery. I have written a PowerShell script that takes care of the above requirement. WebPart.txt file contains the name of the webparts that needs to be deleted from the page.
-------------------
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WebPartPages")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")
$url = "http://myserver"
$WebPageUrl = "Pages/Default.aspx"
$wpNames = Get-Content "c:\Powershell\webparts.txt"
$SPSite = New-Object Microsoft.Sharepoint.SPSite($url)
$SPWeb = $SPSite.OpenWeb()
$SPWeb.Title
foreach ($wpName in $wpNames)
{
$SPWebPart = $SPWeb.GetWebPartCollection($WebPageUrl,
[Microsoft.SharePoint.WebPartPages.Storage]::Shared)
$SPWebPart | select Title
$count = $SPWebPart.Count
for ($k = 0; $k -lt $count; $k++)
{
$wp = $SPWebPart[$k]
if ($wp.Title -eq $wpName)
{
$SPWeb = $SPSite.OpenWeb()
$pubweb = [Microsoft.Sharepoint.Publishing.PublishingWeb]::GetPublishingWeb($SPWeb)
$pubweb
$d = $pubweb.GetPublishingPages()
$SPPage = $d.get_Item($WebPageUrl)
$Page = $SPPage.ListItem.File
if ($Page.Level -eq [Microsoft.SharePoint.SPFileLevel]::Checkout)
{
$SPWeb.CurrentUser.LoginName
$Page.UndoCheckOut()
$Page.CheckOut()
$SPWebPart = $SPWeb.GetWebPartCollection($WebPageUrl,[Microsoft.SharePoint.WebPartPages.Storage]::Shared)
$SPWebPart.Delete($wp.StorageKey)
$SPWeb.Update()
$SPPage.CheckIn("Checked in")
$Page.Publish("Published")
$SPWeb.Update()
Write-Host " $wpName Deleted"
}
else
{
$SPPage.CheckOut()
$SPWebPart = $SPWeb.GetWebPartCollection ($WebPageUrl,Microsoft.SharePoint.WebPartPages.Storage]::Shared)
$c = $wp.StorageKey
$c
$SPWebPart.Delete($c)
$SPWeb.Update()
$SPPage.CheckIn("Checked in")
$Page.Publish("Published")
$SPWeb.Update()
Write-Host "$wpName Deleted and Checked in"
}
}
else
{
Write-Host " $wpName not found"
}
}
}
$Page.Publish("Published")
$SPWeb.Update()
how do you create sharepoint webpart page using powershell?
ReplyDeleteCan you clarify if you want to add webpart to a sharepoint page?
ReplyDeleteHelp me how to add custom webparts to pages in powershell scripts
ReplyDeleteDoes the text file contain each name on a new line, or is it deleted by commas, semi-colonts, etc? Could you maybe add just a brief example of the text file contents. Thanks
ReplyDeletedelimited*
DeleteGet-Content looks for each item on a new line.
DeleteCan i also delete a webpart by it's ID and not by it's name?
ReplyDelete