Add web part to the page

21/10/2012 15:10

Add web part to the page

 

$serverUrl="https://fastlanessl"
$assembly=[void][reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
 
#you have to get the web, where you want to add the webpart, you can also include everything into a function and call the function, when iterating, this is explained in no. 2
 $site = Get-SPSite -Identity $serverUrl
 $web = $site.RootWeb
 
#first you have to check out the file/page, if publishing/versioning is disabled, then you can skip this step
 $file = $web.GetFile("/Pages/wpTest.aspx")
 #$file.CheckOut()
 #initialize the webpart-manager and locate it to the page
 $webpartmanager = $web.GetLimitedWebPartManager("https://fastlanessl/Pages/wpTest.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
 
 #see list of web parts on the page
  $webpartmanager.WebParts
  
 #Add web part to the page
 $webpart = new-object ([Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart])
 $webpart.Title = "New Content Query WP"
 $webpart.ChromeType = [System.Web.UI.WebControls.WebParts.PartChromeType]::None;
 #if your webpart does need some properties to be set, do it now
 $webpartmanager.AddWebPart($webpart, "Zone1",0); #the code in the brakets adds the $webpart to the mentioned zone and sets the sorting of the webpart on the first place
 $webpartmanager.SaveChanges($webpart)
 $web.Update()
 $webpartmanager.Dispose();
 

Close and Delete Web Part

 
#close web part
 
#select web part
$webpart=$webpartmanager.WebParts[0]
$webpartmanager.CloseWebPart($webpart)
$webpartmanager.SaveChanges($webpart)
 
#delete web part
$webpartmanager.DeleteWebPart
 
#no save changes method used
 

Add custom Web Part to the page

 
#use script above, but you have to load your custom assembly (e. g. my project was 'Skusky' and 'Skusky.dll' assembly)
[void][System.Reflection.Assembly]::LoadWithPartialName("Skusky")
 
#use your custom wp class to create new wp instance (in my project it was 'VisualWebPartForResources' namespace with 'VisualWebPartForResources' class)
$webpart = new-object ([Skusky.VisualWebPartForResources.VisualWebPartForResources])