Tuesday, April 17, 2012

Few Web Part operations using PowerShell

Leave a Comment

To create this script, open notepad or any other text editor and save it as .ps1

            1.   Firstly lets show up list of web parts from web on power shell Console

$site = Get-SPSite("site  url");
$web = $site.RootWeb;
$list = $web.Lists["Web Part Gallery"]
$listItems = $list.GetItems()

$listitems | ForEach-Object{ Write-Host $_.Title -Foregroundcolor red -Backgroundcolor green};


2.  Lets get list of web parts on page using Power shell

$site = Get-SPSite("site url");
$web = $site.RootWeb;
$webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webparts = $webpartManager.Webparts

           $webparts | ForEach-Object { Write-Host $_.DisplayTitle }

             3.   Remove WebPart from Page

 $site = Get-SPSite("site url");
 $web = $site.RootWeb;

// Get instance of WebPart Manager on the page
 $webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

// Get all the webparts on page
$webparts = $webpartManager.Webparts

//Get id of webpart to be deleted.
$webpartID = $webparts[1].ID

$webpartManager.DeleteWebPart($webparts[$webpartID]);

0 comments: