Affichage des articles dont le libellé est custom webpart. Afficher tous les articles
Affichage des articles dont le libellé est custom webpart. Afficher tous les articles

mardi 13 septembre 2011

Add custom webpart to a page using power shell

In one of my client, I had to import a webpart in the webpart gallery and add this webpart to the welcome page using Power Shell.
Here is the script I've made.Hope this will help.

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell" ) -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")

$site = new-object Microsoft.SharePoint.SPSite("http://mysite");
$web = $site.OpenWeb()
$fileDWP = $saveFolder + "myCustom.dwp"
$errorMsg = ""

[Microsoft.SharePoint.SPList]$wpList = $site.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog)
$fileStream = ([System.IO.FileInfo](Get-Item $fileDWP)).OpenRead()

[Microsoft.SharePoint.SPFolder]$wpFolder = $wpList.RootFolder
[Microsoft.SharePoint.SPFile]$wpFile = $wpFolder.Files.Add("myCustom.webpart", $fileStream, $true)

$wpFile.Update();

[System.Xml.XmlReader]$xmlReader = [System.Xml.XmlReader]::Create($wpFile.OpenBinaryStream())
[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);
[Microsoft.SharePoint.SPFile]$defaultPage = $pubWeb.DefaultPage;
[Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager]$wpManager = $defaultPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$myCustomWP = $wpManager.ImportWebPart($xmlReader,[ref]$errorMsg)
$wpManager.AddWebPart($infoWp, "Right", 1);
$fileSream.Close()
$xmlReader.Close()
$pubWeb.Close()
$web.Dispose()
$site.Dispose()

write-host "Done"