SP 2013 - Use PowerShell to Add a Custom Web Part to a Page

Hello Community,
I need to add a custom web part to a page using PowerShell - has anyone done this and if so please provide guidance and code examples.
Thanks!
Tom
Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award -
Linked-In - SharePoint Gypsy

BTW, here is my current code:
#$web= Get-SPWeb -Identity "http://c4968397007/sites/BRE"
$Url = "http://c4968397007/sites/BRE"
$pageUrl = "/SitePages/Home"
$webpartzone = 2
$index = 0
$fileName = "wp_DistrictHomePage_VisualWebPart1.webpart"
$web = Get-SPWeb $Url
$web.AllowUnsafeUpdates=$true
 $webPartGallery = $web.Lists["Web Part Gallery"]
 Write-Host "Searching webpart $fileName in web part gallery"
  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");
Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award -
Linked-In - SharePoint Gypsy

Similar Messages

  • Add a custom web part-tasklist- in my MySite Web Appln

    hi,
    In my MySite home page, i would like to add a web part/UI which displays the my pending  approvals in my KM web application.
    as i  will be the approver of many documents uploaded by users in the KM site.
    how can i  create this UI and show this on my MySite Web Appln and be available whenever a user logged in.
    as per my understanding mysite will be created when he clicks on the  top right corner - "sites" link in my Km web appln
    after i configure  Uuser profile service apln. and create a  mysite host  site template. and i have enabled  the option of "enable selef site creation ".
    so how can i add this web part on page load / on site creation of mysite web appln.
    help is appreciated.

    To configure Person Sites in SP 2013 go through the following article.
    https://www.nothingbutsharepoint.com/sites/itpro/pages/sharepoint-2013-creating-and-configuring-mysite.aspx
    When you are on your personal site on quick launch (left navigation) you will see Tasks option. This will be roll-up of all tasks. I am pretty sure you can use this as per your need as it gives different options e.g. Active, Completed and also there is a
    filter as well.
    Read more about this here
    http://blog.blumshapiro.com/blog/2013/06/11/aggregate-all-of-your-tasks-with-sharepoint-2013/
    Amit

  • Using context menu within a custom web part

    Hello,
    I'm fairly new to SharePoint and currently experimenting with some stuff.
    Now I have a list with folders and documents and instead of the regular list view, I've created a custom (visual) web part that shows the list in a sort of tree.
    In this tree I want to add a control for each document only that has the same appearance as the default context menu found in the standard list views.
    The long term goal is to have a custom (visual) web part, that shows the hierarchical structure of the list and has a (on hover only) context menu for the documents.
    I do have extended experience with ASP.Net, but I cannot find any resource to add the context menu (or one that looks, feels and behaves the same) at will at self defined location.
    Note that by default these items don't have a context menu, so how to add it in the first place?
    Your help would be greatly appreciated!
    Stefan

    I would start by looking at the HTML/Javascript structure of the ECB menus (drop down menus on itmes) and see if you can replicate the HTML snippet in your custom control.
    Nikolas Charlebois-Laprade Microsoft Certified Professional & Software Engineer http://nikcharlebois.com
    In the end I ended up using this method, unfortunately...
    However the structure (read look-and-feel) is not identical to the ECB and more modern.
    For example, all actions are icons aligned at the right of each row and appear while hovering over that one row.
    It has been a lot of work to extract the Javascript from the ECB to get everything working, especially regarding deleting and adding items from/to a list.

  • SharePoint 2013 RSS Viewer not loading when other Custom web part using Update Panel or Ajax Timer control

    Hi,
    SharePoint 2013 RSS
    Viewer web part failing to complete loading when the page loads.
    This happens when having RSS Viewer and then adding a Custom webpart with an updatepanel and timer control.
    I  had used Ajax update panel and timer control to load the web part asynchronously after the main page is fully loaded.
    The RSS-Viewer web part hangs in loading state while the custom webpart loads just fine.
    The issue occurs when an like button click or Timer Tick event fires after the page
    is loaded.
    Haven't been able to track the issue.
    Couple of workaround I tried to call a server side button click event from the custom web part after the page gets fully loaded using JQuery shown below did not work out either.
     $(document).ready(function () {
                $('#<%= netButton2.ClientID %>').click();
    And 
    document.onreadystatechange = function () {
                if (document.readyState == "complete") {
                    $('#<%= netButton2.ClientID %>').click();
    Please let me know how to resolve this issue.
    Thanks,
    Franklin

    Hi Johan,
    The assignment of this user on the given task might be corrupted. Try to remove the resource from the task, publish the project, assign the resource again and publish again the project. If it is not working, try to unpublish the task (column "publish")
    and publih it again.
    Hope this helps,
    Guillaume Rouyre, MBA, MVP, P-Seller |

  • How to add the Note board web part to a page with powershell

    Hi everyone,
    I've been looking around everywhere but haven't seen it explicitly mentioned. 
    Does anyone know how to add the Note Board web part to a Team Site page, e.g. Non-publishing site, Left Zone, First webpart in the zone in powershell?
    Examples like this one http://adicodes.com/adding-web-part-to-page-with-powershell/ only talk about custom web parts uploaded from a local drive.
    The example here looks good - http://spcrew.com/blogs/lists/posts/post.aspx?id=21 but is it for the Page Viewer Web Part. How would you go about getting the correct name for the note board web part and configuring it? 
    Many Thanks,
    Ashley
    function main(){
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    $url = "http://sp2010dev1/sites/test1"
    $OpenWeb = Get-SPWeb $url
    $OpenWeb
    $OpenSite = Get-SPSite $url
    $file = $OpenWeb.GetFile("http://sp2010dev1/sites/test1/SitePages/test1.aspx")
    $WebPartManager = $file.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    Add-PageViewerWebPart "http://sp2010dev1/sites/test1" "http://sp2010dev1/sites/test1/SitePages/test1.aspx" "Body" 0 "SPCrew Site" "sp2010dev"
    $OpenWeb.Dispose()
    function Add-PageViewerWebPart($SiteURL, $pageUrl, $webpartzone, $index, $title, $content)
        $site = new-object Microsoft.SharePoint.SPSite($SiteURL)
        $web=$site.OpenWeb()
        $webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
        $webpart = new-object Microsoft.SharePoint.WebPartPages.PageViewerWebPart
        $webpart.ChromeType = [System.Web.UI.WebControls.WebParts.PartChromeType]::TitleOnly;
        $webpart.Title = $title
        $webpart.ContentLink = "http://www.spcrew.com";
        $webpartmanager.AddWebPart($webpart, $webpartzone, $index);    
        $web.Close()
        $site.Close()
    function Get-SPSite([string]$url) {
        New-Object Microsoft.SharePoint.SPSite($url)
    function Get-SPWeb([string]$url) {
        $SPSite = Get-SPSite $url
        return $SPSite.OpenWeb()
        $SPSite.Dispose()

    Hi,
    According to your post, my understanding is that you wanted to add the Note board web part to a page with PowerShell.
    The name of the Note Board web part is SocialCommentWebPart.
    I recommend to use the powershell code below:
    $pageUrl="http://sitename/SitePages/test.aspx"
    $SiteURL="http://sitename"
    $site = new-object Microsoft.SharePoint.SPSite($SiteURL)
    $web=$site.OpenWeb()
    $webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    $webpart = new-object Microsoft.SharePoint.Portal.WebControls.SocialCommentWebPart
    $webpart.title="Note Board"
    $webpartmanager.AddWebPart($webpart, "MiddleZone", 0);
    $web.Close()
    Then the Note board web part will be added to the page.
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Custom web parts in SharePoint 2013 becomes inactive when the session is idle for long time.

    Hi,
    We have a search center site with custom web parts and custom master pages. When the session is inactive for long time all the custom web parts in the page doesn't work, unless we close the browser and open it. Where as this is not the case with the
    OOB web parts. We are not able to identify the root cause as it works with OOB web parts and not the custom web parts.We were able to find that by increasing the session timeout of the web application we can avoid this issue.We do not want to increase the
    session timeout as the OOB web part works perfectly even when the user session is idle for long time.Is there any other alternative where we can acheive the same for custom web parts when the session is idle for long time?
    Thanks,
    Saranya

    Hi Saranya,
    According to your descirption, my understanding is that when the session is long time idle ,then custom web part will not work.
    I suggest you check if you have enable the session in the Page Level in the web.config. By default SharePoint disable the session state.
    In the web.config, you will see <page enableSessionState> tag. You can modify like below and test if it works.
    <pages enableSessionState=”true” ….. />
    Here is a detailed thread for your reference:
    Use Session State in SharePoint
    Best Regards
    Zhengyu Guo
    TechNet Community Support

  • How to fix javascript error/bug on custom web part of SharePoint 2013

    I have a custom web part with serveral business fields. This web part is installed on DispForm, EditForm an NewForm.
    But, I click on Attach File button and a javascrit error is throw on my browser's status bar.
    Line: 5279
    Character: 5
    Code: 0
    URI: http://mysite:4000/_layouts/15/form.debug.js?rev=vyMg8qjZfJ8La1jn7bQ2cg%3D%3D
    How to solve this problem? I think it is a javascript conflict
    Tarcísio Corte [email protected]

    Hi,
    1. You can create a simple demo web part without your custom code firstly, then insert it into your form pages to see if the similar issue would occur. If it works, then add your
    other code into it one after one. By doing this, it will be easier to find out the root cause of this issue.
    2. What browser do you use? Please try to use IE 10(SharePoint 2013), IE8(SharePoint2010).
    3. You can also debug your code using IE F12 Developer Tools.
    http://blogs.msdn.com/b/kaevans/archive/2011/04/25/debugging-javascript-with-the-ie-developer-tools.aspx
    If the issue still exists, I can suggest you provide more information for further research.
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Create custom web-part page with OOTB page layout using CSOM (Javascript)

    Hi,
    I need to create a custom webpart page with a OOTB page layout (eg. Header 3 column footer) using JSOM.
    I found a link to do this using CSOM: http://spdevlab.com/2013/03/28/creating-wiki-web-part-and-publishing-pages-via-csom-in-sharepoint-2010/
    But here i have to copy the page template from 15 hive and store it in a resource file and I am also getting error as "The request message is too big" and to fix this I need to run a powershell script but I need the code to run in SharePoint online
    also.
    Isn't there a simpler piece of code in which I can enter the name of the page layout(OOTB/Custom) while creating a page in JSOM as we have in SSOM?
    Thanks for the help
    sunny

    Hi,
    According to your post, my understanding is that you want to create a custom web part page layout template.
    There are some articles about how to create the custom web part page layout template, you can refer to them.
    http://www.manageprojectsonsharepoint.com/blog/2011/03/14/creating-your-own-web-part-page-layout-template/
    http://sandeeppawar.blogspot.com/2012/06/create-custom-web-part-page-template.html
    http://doitwithsharepoint.blogspot.com/2011/08/create-web-part-pages-with-custom.html
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • How to add a custom web project to creator?

    I am using Creator EA2. I want to add a custom web project, which is created based on standard web project, to Creator. I wonder if it is possible by creating a jar and put it into a directory or I should develop a plugin with layout description files, templates?
    Thanks
    jnewbie

    If your struts-enabled project is already compatible with Creator (i.e. you can open it in the IDE) you can get close to what you way using the project template facility available in EA2.
    Select Tools->Project Template Manager. From the template manager dialog, click the Add... button and browse to your struts project. The project should appear under the My Templates node in the dialog. Close the dialog and bring up the New Project Wizard. You should see a new project category called My Templates which should contain an entry to your custom project. You can now select this project and proceed through the wizard which will actually clone the project for you as if it were a custom project type.

  • Why i do not have "Custom" category when trying to add a new web part

    I have deployed a .wsp solution to my web application as follow, using Visual studio:-
    But when I try to add this web part to my brand new enterprise wiki site collection, I can not see any “custom” web part area as follow:-
    Baring in mind that we have an old site collection also of type enterprise wiki and is inside the same web application, which have the “custom” tab visible as follow:-

    Hello john, 
    did you try to disable and enable again the WebApp feature that hosts the webpart, on central administration?
    If it's not working, try to change the scope of you feature to "site collection" instead of "web application"
    now i try retracting then re-deploying the farm solution again but still it will work on the old site collection only.
    Now seems i am a bit confused as i do not have much knowledge in developing solution. now the solution i deployed is mainly for fixing Redirect problem in SharePoint managed metadata navigation, the OnInit method is as follow:-
    protected override void OnInit(EventArgs e)
    var request = HttpContext.Current.Request;
    var response = HttpContext.Current.Response;
    if (!String.IsNullOrEmpty(request.QueryString["TreeField"])
    && !String.IsNullOrEmpty(request.QueryString["TreeValue"]))
    response.Redirect(String.Format("{0}?TreeField={1}&TreeValue={2}",
    SPContext.Current.ListItem.ParentList.DefaultViewUrl,
    request.QueryString["TreeField"],
    request.QueryString["TreeValue"]));
    else if (!String.IsNullOrEmpty(request.QueryString["TreeField"]))
    response.Redirect(String.Format("{0}?TreeField={1}",
    SPContext.Current.ListItem.ParentList.DefaultViewUrl,
    request.QueryString["TreeField"]));
    base.OnInit(e);
    and the solution have the following settings inside the visual studio , where the Site URL refers to my development machine URL . but this did not cause any problem inside the live serve old site collection:-
    and when i deploy the farm isolation i did the following steps :-
    - I copy the wsp from the visual studio project.
    - Then i run the following command inside the Live server "stsadm -o addsolution –filename [c:....]\WikiKnowledgeBaseRedirect.wsp"
    - Inside the live server i went to "central administration>>system settings>> Manage farm solutions>>click on WikiKnowledgeBaseRedirect>>click on deploy solution >>select the web application from the “Deploy To?" drop
    down".
    now as i mentioned before the wsp worked well inside my old site collection, although the site URL refers to the test server site collection (not sure if this was overridden when I deployed the solution to live server).  but inside the new site collection
    i can not find this solution inside the "site setting>>site collection features" nor inside the "site settings>>web designer gallery>> web part"? can u advice based on the above ?

  • 2013 Custom Web Parts in Page Layouts not showing for users

    Custom Web Parts in Page Layouts not showing for users
    I have created a master page in the root site collection for a subsite I am developing. I created content types and custom page layouts for the pages within the subsite.
    I used the snippet tool in the design manager to create web parts and page field markup which I copied into the custom layout HTML pages in the root site collection. For instance I have an image viewer web part that I place there to serve as a section title.
    The problem is that I can see all these customer layout page parts no problem but my users cannot. This leads me to believe its permissions, I am site owner of both the subsite and root site collection.
    The users that cannot see the web parts are site members of the site and restricted read users on the root site collection (where the layouts are stored).
    What gives I'm finding it hard to understand why a snipet generated web part wouldn't show in all pages created from that layout page.
    Any help would be appreciated, Havent found anything on this issue online. weird.

    It is a permission issue indeed. Fix is simple, make sure you check out the page layout page, then check it back in as published version.
    John Architect

  • How do I add a search web part to search ONLY a subsite?

    I'm trying to add a search web part into a subsite that will search ONLY that specific subsite for documents. Not the entire site collection or anything else.   Everything I've looked at doesn't address this specifically.  I want a user
    to be able to type in a word like "SharePoint"  and all it displays is the results for any document in that subsite that has "SharePoint" in the title of the document.   I'm assuming that it's not very convoluted to do.

    You can use site "search settings" and "search scope" to achieve this , you can use any of these method -
    Configure Site settings -> Search settings to default to the contexual scope. This will pass current site  url to search results page to filter current site result only.
    Use refinement web part on the search results page to filter results from a specific sub-site.
    Create a search scope for the subsite , some example here for Sp2010 and 2013-
    http://www.bentedder.com/create-a-search-scope-for-a-sharepoint-2010-list-or-library/
    http://techmikael.blogspot.in/2013/04/limiting-search-results-in-sharepoint.html
    Thanks
    Ganesh Jat [My Blog |
    LinkedIn | Twitter ]
    Please click 'Mark As Answer' if a post solves your problem or 'Vote As Helpful' if it was useful.

  • How to enable a custom web part class file to be refreshed at regular interval of time, without affecting the entire page where its placed.

    Hi,
    I am calling a web service in the web part class file where it gets the data. I need to call the service at regular intervals of time which is in the web part, is there a way to get the web part refreshed automatically at certain intervals of time.
    Rayudu

    You can use Ajax for automatic refreshing.
    Add a timer control into an Ajax Update panel within your custom web part and execute your code to refresh the field values within the Timer_Tick() event.
    You can also control the timer interval to 10 minutes or so using the Timer.Interval property.
    This will always enable your page to remain with only the web parts getting refreshed.
    I just found
    a blog post which describes this in detail with screenshots.

  • Is there a way to allow contributor users to add web parts to a page without granting them "Add and Customize Pages" permission?

    I am working on an enterprise wiki site collection, and when contributor users try to add web parts they will get the following error:-
    A Web Part or Web Form Control on this Page cannot be displayed or imported. You don't have Add and Customize Pages permissions required to perform this action.
    So I granted the Contribute Permission level an extra permission which is “Add and Customize Pages”. Now contributors will be able to add/edit/delete
    web parts. But they will have extra permissions that I do not want them to have , such as changing the design and customize some page layouts, also they can access the site settings and create site columns !!.
    So my question is basically if there is another way to allow users with contribute permission to be able to add web parts without granting any extra permission. In other words to treat adding web parts as normal content such as image, Text ,tables ?
    Thanks

    I dont think so.
    http://technet.microsoft.com/en-us/library/cc288074%28v=office.14%29.aspx
    Add and Customize Pages
    Add, change, or delete HTML pages or Web Part pages, and edit the Web site by using a Windows SharePoint Services-compatible editor.
    View Items, Browse Directories, View Pages, Open
    Design, Full Control 
    If this helped you resolve your issue, please mark it Answered. You can reach me through http://freeit-support.com/
    so there are not any workarounds or any custom settings which i can use to implement any of these:-
    - To force Contributor users to add web parts without granting them "Add and Customize Pages"
    - If i grant them "Add and customize Pages" permission, to stop the ability to access the site settings ?
    Please can any one advice on this , as it is causing a lot of confusion,,, and i can not live with the face that Contributor users can access and modify site settings. the other approach will be is that i will stop using web parts. but one of our main reasons
    we decide to use SharePoint is the ability to add web parts, especially the Visio & Excel web access web. thanks in advance for any advice ..

  • Best Practices in SharePoint 2010 ( Out of the box feature vs Custom Web Part, development )

    Hi
    How do we differentiate on when to allow custom web parts and when to use out of the box.
    What are the performance issues involved when we deploy a custom web part into the SharePoint server. 
    Why do some companies prefer to allow only out of the box features, and no custom work is done?

    SharePoint is a powerful, flexible server product that can provide a wealth collaboration environment right out of box.
    Best answer for your question is depend upon your requirement. Sometime Out of Box features will solve all the problem with little designing. But sometime your requirement need a Custom Web part / solution.
    With OOTB implementation the big advantage is easy to trouble shoot & fix the issues. You will also found tons of blogs on internet for OOTB features. In custom development, its hard to troubleshoot & identifying whether its SharePoint issue or Custom
    code issue.
    check the below article for more ideas.
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/1e7845ef-61e0-4d01-bb6c-92519e6d7139/sharepoint-2010-outofbox-best-practices?forum=sharepointgeneralprevious
    http://www.cdh.com/media/articles/Pages/SharePoint-out-of-the-box---To-customize-or-not-to-customize.aspx
    Master List of SharePoint 2010 On-Premises Custom Development Best Practices
    http://i.zdnet.com/whitepapers/Quest_WPW_SharepointDev_Custom_US_KS_v3.pdf
    Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog

Maybe you are looking for