SharePoint Pals
 | Sign In
How to Add AppParts to Publishing Pages in SharePoint 2013 using PowerShell
by Sathish Nadarajan 18 Oct 2015
SharePoint MVP
Today  :   23     Total  :    4263

In the previous articles, we saw how to add the Content Editor WebPart and Script Editor WebParts, even the custom WebParts as well. In the same manner, in this article, let us see how to add AppParts to Publishing Pages in SharePoint 2013 using PowerShell.

One thing, we need to remember is, we cannot directly exact the WebPart file from the .APP File. Hence, during the development time, before the deployment package, we need to add the AppParts manually to the screen. Then export the WebPart and save the AppParts as .WebPart Files.


Then the exported File with the extension of .WebPart will be packed along with your deployment package.

Now, let us see the below script.

 ## Description	: Create the publishing pages based onthe XML input 
 ## Author		: Sathish Nadarajan
 ## Date			: 07-Aug-2015
 # ============================================ Setup Input Paths ===========================================================
 $Host.UI.RawUI.WindowTitle = "-- Create Pages --"
 $StartDate = Get-Date
 Write-Host -ForegroundColor White "------------------------------------"
 Write-Host -ForegroundColor White "| Create Publishing Pages |"
 Write-Host -ForegroundColor White "| Started on: $StartDate |"
 Write-Host -ForegroundColor White "------------------------------------"
 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 $LogFile = ".\CreatePage-$LogTime.rtf"
 #start-transcript $logfile
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 $ErrorActionPreference = "Stop"
 function AddPowerShellSnapin()
         Write-Host "Adding PowerShell Snap-in" -ForegroundColor Green
         # Try to get the PowerShell Snappin.  If not, then adding the PowerShell snappin on the Catch Block
         Get-PSSnapin "Microsoft.SharePoint.PowerShell" 
         if($Error[0].Exception.Message.Contains("No Windows PowerShell snap-ins matching the pattern 'Microsoft.SharePoint.PowerShell' were found"))
             Add-PSSnapin "Microsoft.SharePoint.PowerShell"
     Write-Host "Finished Adding PowerShell Snap-in" -ForegroundColor Green
 function AddPage
         Write-Host "Entering into AddPage Method" -ForegroundColor Green 
         # Get the SiteURL
         $SiteUrl = $SiteConfig.Config.SiteURL;
         # Get the WebURL
         $WebUrl = $SiteConfig.Config.WebURL;
         Write-Host "WebUrl : $WebUrl" -ForegroundColor Green 
         # Get the Error Message
         $ErrorMessage = $SiteConfig.Config.ErrorMessage;
         # Initialize the Site Object
         $Site = Get-SPSite $SiteUrl
         Write-Host "Site: $Site" -ForegroundColor Green
         # Get the Publishing Site based on the SPSite
         $PubSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($Site)
         Write-Host "Pubsite: $PubSite" -ForegroundColor Green
         # Get the SPWeb Object
         $Web = Get-SPWeb $WebUrl
          Write-Host "Web: $Web" -ForegroundColor Green
         # Below lines are required to GetPublishingPage Error
         $correctId = $Web.Lists["Pages"].ID
         Write-Host "correctId: $correctId" -ForegroundColor Green
         $Web.AllProperties["__PagesListId"] = $correctId.ToString()
         $Web.AllProperties["__PublishingFeatureActivated"] = "True"
         Write-Host "After web update" 
         # Initialize the PublishingWeb based on the SPWeb
         $PubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
         # Get the PageLayouts Installed on the Publishing Site
         $Layouts = $PubSite.GetPageLayouts($False)
         foreach($Page in $SiteConfig.Config.Pages.Page)     
             # Get our PageLayout
             $PageLayout = $Layouts[$Page.PageLayoutRelativeURL]
             $PublishingPage = $PubWeb.GetPublishingPage($WebUrl + "Pages/" + $Page.URL)
             Write-Host "Adding the Publishing Page" -ForegroundColor Green 
             # Verify whether the page is already there or not.
             if($PublishingPage -eq $null)
                 # If not, Create a new publishing page.
                 $PublishingPage = $PubWeb.AddPublishingPage($Page.URL, $PageLayout)
             if($PublishingPage.ListItem.File.CheckedOutByUser -eq $null)
                 # Though it is newly created or already there, checkout.
             # Assign the Title for the Page
             $PublishingPage.Title = $Page.Title
             # Update the Page
             Write-Host "Successfully Added the Page" -ForegroundColor Green 
             Write-Host "Adding the WebParts into the Page" -ForegroundColor Green 
             foreach($WebPart in $Page.WebParts.WebPart)
                 # Get the LimitedWEbPartManager
                 $limitedWebPartManager = $PublishingPage.ListItem.File.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);
                 # Initialize the XmlReaderSettings Object which is required for the XmlReader Object
                 $xmlReaderSettings = New-Object System.Xml.XmlReaderSettings
                 # Create the XmlReader Object by using the WebPart Definition file and the ReaderSettings Object
                 $xmlReader = [System.Xml.XmlReader]::Create($scriptBase + "\" + $WebPart.LocalWebpartPath,$xmlReaderSettings);
                 #Add Web Part to catalogs folder and Get the WebPart Definition Object based on the webpart definition xml file     
                 $oWebPartDefinition = $limitedWebPartManager.ImportWebPart($xmlReader,[ref]$ErrorMessage);
                 # Add the WebPart to the WebPartManager by specifing the Zone and the Index.
             Write-Host "WebParts Added Successfully" -ForegroundColor Green
             # Check in the Page with Comments
             # Publish the Page With Comments
         Write-Host "Custom Exception Happened : " + $Error[0].Exception.Message -ForegroundColor Red  
     $ConfigXmlPath = $scriptBase + "\" + "CreatePublishingPages.xml"
     Write-Host "Read the Config Values" -ForegroundColor Green 
     # Get the Content of the Config Xml
     [Xml]$SiteConfig = Get-Content $ConfigXmlPath  
     Write-Host "Script Execution Completed Successfully" -ForegroundColor Green 
     Write-Host "Custom Exception Happened on Main : " + $Error[0].Exception.Message -ForegroundColor Red  

The Configuration XML looks like below.

 <?xml version="1.0" encoding="utf-8"?>
   <ErrorMessage>Some Exception Occured During the Page Creation Process</ErrorMessage>
       <Title>Test Page 6</Title>
       <CheckinComment>Test Checkin Comment</CheckinComment>
       <PublishingComment>Test Publishing Comment</PublishingComment>

The above script will read the values from the config file and create the pages, add the app parts to the publishing pages.

Happy Coding,

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile


Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community

SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to in a word document.

Related Resources

Recent Tweets

Twitter October 23, 22:21
How to Add/Remove User Custom Actions (in Site Actions Menu) Programmatically using CSOM PNP in SharePoint -

Twitter October 21, 21:34
How to Add a JS Link Reference to the Display Form or Any other ASPX Programmatically using CSOM PNP in SharePoint -

Twitter October 20, 13:01
How to Add a JS Link Reference to the NewForm and EditForm Programmatically using CSOM PNP in SharePoint Office 365-

Twitter October 12, 12:15
How to Deploy Provider Hosted Apps (Add-Ins) by App Stapling in SharePoint Office 365 -

Twitter October 11, 13:39
How to Deploy Provider HostedApp programmatically using CSOM in SharePoint Office 365 Activating Developer Feature -

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation