如何在PowerShell脚本中向页面添加自定义Web部件?

时间:2010-12-04 12:21:00

标签: sharepoint scripting powershell

我创建了一个自定义的webpart并添加到webpart库中。我需要在我的页面中添加该webpart控件。 请帮助我如何在PowerShell脚本中实现这一点。

3 个答案:

答案 0 :(得分:2)

使用GetLimitedWebPartsManager()获取对您网页管理员的引用,然后调用其AddWebPart()方法:

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

有关详细示例,请参阅http://blogs.flexnetconsult.co.uk/colinbyrne/2007/02/10/SharePointPowerShell8TheOneWithTheContactWebPart.aspx

答案 1 :(得分:0)

这是使用powershell将webpart添加到apage的简单脚本,经过测试并且工作正常

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

请注意,将webpart添加到页面导出webpart到本地驱动器和.webpart / .dwp文件将采用xml格式

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"
    }

答案 2 :(得分:0)

这取决于我们的要求,但我们可以使用JavaScript或其他客户端对象模型库将Web部件添加到SharePoint页面。我的建议是,即使您的要求指导您编写PowerShell脚本,请尽可能使用客户端对象模型而不是服务器对象模型。

如果您想直接从XML变量添加,请注意以下这一行:

导入webpart

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

您可以在此处查看更多信息:http://josharepoint.com/2016/02/16/using-powershell-to-add-webpart-to-sharepoint-page-via-csom-in-office-365/