Quick Launch

Adding PageViewer Webpart with PowerShell - SpCrew Blogs
Search
SpCrew Blogs > Posts > Adding PageViewer Webpart with PowerShell
​​​​​​​​​​​​​​​
​​​​​​​​
May 07
Adding PageViewer Webpart with PowerShell

Sometimes you may have a need to add a webpart to a page with powershell. The following code can be used to accomplish such a task. You can check out the following page for a list of webparts available in the Microsoft.SharePoint.WebPartPages namespace: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.aspx

Here is the powershell code. Copy this into a PS1 file and then run from powershell using "./yourscriptname.ps1"

 

function main(){

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$url = "http://sp2010dev1/sites/test1"
$OpenWeb = Get-SPWeb $url
$OpenWeb
$OpenSite = Get-SPSite $url
$file = $OpenWeb.GetFile("http://sp2010dev1/sites/test1/SitePages/test1.aspx")
$WebPartManager = $file.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
Add-PageViewerWebPart "http://sp2010dev1/sites/test1" "http://sp2010dev1/sites/test1/SitePages/test1.aspx" "Body" 0 "SPCrew Site" "sp2010dev"
$OpenWeb.Dispose()
}

function Add-PageViewerWebPart($SiteURL, $pageUrl, $webpartzone, $index, $title, $content)

{
    $site = new-object Microsoft.SharePoint.SPSite($SiteURL)
    $web=$site.OpenWeb()
    $webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    $webpart = new-object Microsoft.SharePoint.WebPartPages.PageViewerWebPart
    $webpart.ChromeType = [System.Web.UI.WebControls.WebParts.PartChromeType]::TitleOnly;
    $webpart.Title = $title

    $webpart.ContentLink = "http://www.spcrew.com";
    $webpartmanager.AddWebPart($webpart, $webpartzone, $index);    

    $web.Close()
    $site.Close()
}

function Get-SPSite([string]$url) {
    New-Object Microsoft.SharePoint.SPSite($url)
}

function Get-SPWeb([string]$url) {
    $SPSite = Get-SPSite $url
    return $SPSite.OpenWeb()
    $SPSite.Dispose()
}

main

Comments

Thank you!

Mr. Hahner, that is fabulous!  Thanks for that!
 on 5/8/2012 5:45 PM

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Posted By *


Title


Body *


Attachments