开发者

How to add custom webparts to pages in powershell scripts?

I have created a custom webpart and added to the webpart gallery.I need to add that webpart control in my page. Please help me how 开发者_JAVA百科to achieve this in powershell scripts.


Use GetLimitedWebPartsManager() to obtain a reference to your page's manager, then call its AddWebPart() method:

$mgr = $web.GetLimitedWebPartManager($yourPageUrl,
    [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$mgr.AddWebPart($yourWebPart, "YourZone", 0);

See http://blogs.flexnetconsult.co.uk/colinbyrne/2007/02/10/SharePointPowerShell8TheOneWithTheContactWebPart.aspx for a detailed example.


Here is simple script to add a webpart to apage using powershell Which is Tested and working fine

http://soreddymanjunath.blogspot.in/2014/07/add-webpart-to-page-using-powershell.html

Please note that to add a webpart to a page export webpart to your local drive and .webpart/.dwp file will 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"
    }


It depends on our requirements, but we could use JavaScript or other Client Object Model libraries to add a web part to SharePoint page. My advice is, even if your requirements guide you to write PowerShell script, try to use Client Object Model instead Server Object Model, whenever possible.

If you want to add directly from XML variable take care about this line:

Import the webpart

$wp = $webpartManager.ImportWebPart($WebPartXml.OuterXml)

You can see more information here: http://josharepoint.com/2016/02/16/using-powershell-to-add-webpart-to-sharepoint-page-via-csom-in-office-365/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜