SharePoint 2010 - Add WebPart to a Web with PowerShell
-
16-10-2019 - |
سؤال
I want to add a webpart to a great number of existing pages. Is there any PowerShell command to add a webpart to a webpart page?
المحلول
There's no PowerShell Command, but you can use the AddWebPart
method of the SPWebPartManager
class to add the WebPart to a WebPartPage:
http://msdn.microsoft.com/EN-US/library/ms157507(v=VS.90)
You can get a SPWebPartManager
object by calling WebPartManager.GetCurrentWebPartManager
and providing it your WebPartPage
:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webpartmanager.getcurrentwebpartmanager(v=VS.90).aspx
نصائح أخرى
Theres nothing like this OOB, but you have pretty much the same options in PowerShell as in say a console application in C#.
So theres the option of coding your own cmdlet that does this for you.
On NBSP i found this script that should get you going.
Here are some sample powershell scripts for adding webparts to sites:
A nice, simple, clean code for adding a CEWP:
This one adds a customized web-part:
http://www.sharemuch.com/2010/11/17/using-powershell-to-add-and-configure-sharepoint-2010-webparts/
And this adds a page-viewer webpart - Mr. Hahner made this blogpost especially for me! http://spcrew.com/blogs/lists/posts/post.aspx?id=21
Here is a simple script to add a webpart to a page using PowerShell which is tested and working fine.
Please note that to add a webpart to a page export webpart to your local drive .webpart/.dwp file will be in xml format.
cls
asnp "*sh*"
$web=Get-SPweb -Identity "http://SP2013dev.com/sites/addwebpart/"
[xml]$webpartxml= Get-Content -Path "C:\Manju\WPRequest.xml"
$SR = New-Object System.IO.StringReader($webpartxml.OuterXml)
$XTR = New-Object System.Xml.XmlTextReader($SR)
$err=$null
$WebPartZoneID = "Topzone"
$WebPartZoneIndex = 0
try
{
$page=$web.GetFile("Pages/default.aspx");
$bool=$page.CheckedOutBy
if($bool)
{
Write-Host "Page is already Checkout to " $page.CheckedOutBy.UserLogin
$page.UndoCheckOut()
Write-Host "Page is Over ridded by " $web.CurrentUser.DisplayName + " to Add Webpart"
}
$page.CheckOut();
$wmgr=$web.GetLimitedWebPartManager($page, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);
$webpart=$wmgr.ImportWebPart($XTR,[ref]$err);
$wmgr.AddWebPart($webpart,$WebPartZoneID,$WebPartZoneIndex);
$page.CheckIn('dude');
$page.Publish('Adding request Site Webpart')
"Request Site WebPart SucessfullAdded" + (Get-Date -DisplayHint Date) | Out-File -Append "C:\OutPutLog.txt"
$SR.Close();
$XTR.Close();
$web.Dispose()
}
catch
{
$ErrorMessage = $_.Exception.Message
"Request Site WebPart Failure" + $ErrorMessage + (Get-Date -DisplayHint Date) | Out-File -Append "C:\ErrorLog.txt"
}