Skip to content

Instantly share code, notes, and snippets.

@ishajain
Last active September 23, 2020 00:13
Show Gist options
  • Select an option

  • Save ishajain/7476450 to your computer and use it in GitHub Desktop.

Select an option

Save ishajain/7476450 to your computer and use it in GitHub Desktop.
$Url = $(Read-Host -Prompt "Enter site url:")
$web = Get-SPWeb $Url
$web.AllowUnsafeUpdates=$true
function Add-WebPartToPage($pageUrl, $webpartzone,$index,$fileName)
{
$webPartGallery = $web.Lists["Web Part Gallery"]
Write-Host "Searching webpart $fileName in web part gallery" -ForegroundColor Yellow
if($webPartGallery -eq $null)
{
Write-Host("Unable to retrieve Webpartgallery");
}
$webpart = $null;
$webpart=$webPartGallery.Items | ? { $_.Title -eq $fileName}
if($webpart -eq $null) {
Write-Host("Unable to retrieve webpart: $fileName") -ForegroundColor Red
}
else {
Write-Host("----------Adding Webpart--------")-ForegroundColor Yellow
$webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$errorMsg = "";
$xmlReader = New-Object System.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
$webpart = $webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
$webpartmanager.AddWebPart($webpart, $webpartzone, $index);
Write-Host("Webpart is added successfully") -ForegroundColor Green ;
}
}
$SiteURL =$Url
#---------------Test Page----------------------------
$PageName="Test.aspx"
$page=$web.lists["Pages"].Items | ? {$_.Name -eq $PageName}
$page.File.CheckOut();
Add-WebPartToPage "$SiteURL/Pages/$PageName" "Header" 0 "My Custom WebPart"
$page.File.CheckIn("Added Web part to a page");
$page.File.Approve("Added Web part to a page");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment