4

I'm trying to add a page to my search centre in sharepoint 2013. Trying out cSOM too. Here is my code, I am getting a bug Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (400) Bad Request.

function New-SearchResultsPage() 
{

    param(
        [Parameter(Mandatory=$true)][string]$siteurl,
        [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials,
        [Parameter(Mandatory=$false)][string]$PageTitle,
        [Parameter(Mandatory=$false)][string]$PageLayoutName
    )

    try
    {

    # Authenticate with site.
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl) 
    $ctx.Credentials = $credentials

    # Get the SearchResults page layout item needed for setting the
    # page layout list item property for new publishing pages.
    $rootWeb = $ctx.Site.RootWeb
    $mpList = $rootWeb.Lists.GetByTitle('Master Page Gallery')
    $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $camlQuery.ViewXml = '<View><Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">'+$PageLayoutName+'</Value></Eq></Where></Query></View>'
    $items = $mpList.GetItems($camlQuery)
    $ctx.Load($items)
    $ctx.ExecuteQuery()
    $pageLayoutItem = $items[0]
    $ctx.Load($pageLayoutItem)

    # Get publishing web object
    #
    $web = $ctx.Web
    $pubWeb = [Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($ctx, $web)
    $ctx.Load($pubWeb)

    # Setup for blog post creation using CSV file as input.
    #
    $pagesList = $ctx.Web.Lists.GetByTitle('Pages')

    Write-Host ("Creating custom result page")
    Write-Output("Creating custom result page")
    # Create page information instance, update properties, 
    # add it, check it in, publish it, and approve it.
    #   
    $pubPageInfo = New-Object Microsoft.SharePoint.Client.Publishing.PublishingPageInformation
    $pubPageInfo.Name = $PageTitle.Replace(" ", "-") + ".aspx"
    $pubPageInfo.PageLayoutListItem = $pageLayoutItem 
    $pubPage = $pubWeb.AddPublishingpage($pubPageInfo)

    $pubPage.ListItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
    $pubPage.ListItem.File.Publish("")
    #$pubPage.ListItem.File.Approve("")

    $ctx.Load($pubPage) 
    $ctx.ExecuteQuery()
    Write-Host ("Custom result page created !") -ForegroundColor Cyan
    Write-Output("Custom result page created !")
    Write-Host ("Preparing to update page title")
    Write-Output("Preparing to update page title")
    # Page added.  Now retrieve list item, check it out, 
    # update title and page content, and check back in.
    #
    $listItem = $pubPage.get_listItem()
    $ctx.Load($listItem)
    $ctx.ExecuteQuery()

    $file = $listItem.File
    $file.CheckOut()
    $ctx.Load($file)
    $ctx.ExecuteQuery()

    $listItem.Set_Item("Title", $PageTitle)
    $listItem.Update()
    $listItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
    $listItem.File.Publish("")
    #clear$listItem.File.Approve("")
    $ctx.Load($listItem)
    $ctx.ExecuteQuery()

    Write-Host ("Search result page created successfully !") -ForegroundColor Cyan
    Write-Output ("Search result page created successfully !")

    }
    catch
    {
        Write-Host ("Error while creating search result page. Error -->> " + $_.Exception.Message) -ForegroundColor Red
        Write-Output("Error while creating search result page. Error -->> " + $_.Exception.Message)
    }   
}
4

Make sure the proper version of SharePoint 2013 Client Components SDK (SharePoint Server 2013 Client Components SDK) is installed on the client machine.

The following script allows to create a Publishing Page using CSOM:

param (
    [string]$Url,
    [string]$UserName,
    [string]$Password,
    [string]$PageName,
    [string]$PageLayoutName
 )

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Publishing")




Function Add-PublishingPage([Microsoft.SharePoint.Client.ClientContext]$Context, [string]$PageName,[string]$PageLayoutName,[hashtable]$Properties)
{
    $pubWeb = [Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($Context, $Context.Web)
    $pageInfo = New-Object Microsoft.SharePoint.Client.Publishing.PublishingPageInformation
    $pageInfo.Name = $PageName
    $pageInfo.PageLayoutListItem = Get-PageLayout -Context $Context -Name $PageLayoutName
    $publishingPage = $pubWeb.AddPublishingPage($pageInfo)
    $pageItem = $publishingPage.ListItem
    foreach ($p in $Properties)
    {
       $pageItem[$p.Key] = $p.Value
    }
    $pageItem.Update()
    $Context.ExecuteQuery()
}


Function Get-PageLayout([Microsoft.SharePoint.Client.ClientContext]$Context,[string]$Name)
{
    $list = $Context.Site.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)
    $qry = New-Object Microsoft.SharePoint.Client.CamlQuery
    $qry.ViewXml = "<View><Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>$Name</Value></Eq></Where></Query></View>"
    $result = $list.GetItems($qry)
    $Context.Load($result)
    $Context.ExecuteQuery()
    if($result.Count -gt 0) {
       return $result[0]
    }  
    return $null
 }


$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$context.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
Add-PublishingPage -Context $context  -PageName $PageName -PageLayoutName $PageLayoutName
$context.Dispose()

Usage

./Add-PublishingPage.ps1 -Url "http://contoso.sharepoint.com/search" -UserName "username@contoso.onmicrosoft.com" -Password "password" -PageName "CustomResults.aspx" -PageLayoutName "searchresults.aspx"
1

To create a publishing page using either Out of the box or a custom page layout following is the code.

There are 2 things you need to keep in mind to follow the below function

  • If you are using OOB page layout, then we are using CAML query to get page layout as an item
  • If you are using a custom page layout, then we are using a path to get page layout as an item. In below example the custom page layout is assumed to be in custom folder.

#Load SharePoint Client Assemblies 
Try{
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll'
}

catch {
    Throw "Unable to load SharePoint Client runtime"
}


function Create-PublishingPage() 
{

    param(
        [Parameter(Mandatory=$true)][string]$siteurl,
        [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials,
        [Parameter(Mandatory=$false)][string]$PageTitle,
        [Parameter(Mandatory=$false)][string]$PageName,
        [Parameter(Mandatory=$false)][string]$PageLayoutName,
        [Parameter(Mandatory=$false)][bool]$isCustomPageLayout
    )

    try
    {


        # Authenticate with site.
        #
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl) 
        $ctx.Credentials = $credentials


        if($isCustomPageLayout -eq $false)
        {
            # Get the page layout item 
            #
            $rootWeb = $ctx.Site.RootWeb
            $mpList = $rootWeb.Lists.GetByTitle('Master Page Gallery')
            $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
            $camlQuery.ViewXml = '<View><Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">'+$PageLayoutName+'</Value></Eq></Where></Query></View>'
            $items = $mpList.GetItems($camlQuery)
            $ctx.Load($items)
            $ctx.ExecuteQuery()
            $pageLayoutItem = $items[0]
            $ctx.Load($pageLayoutItem)
        }
        else
        {
            # Get custom page layout and convert it to list item
            #
            $PageLayoutName = "/_catalogs/masterpage/Custom Page Layouts Folder/" + $PageLayoutName
            $items = $ctx.Site.RootWeb.GetFileByServerRelativeUrl($PageLayoutName)
            $ctx.Load($items)
            $pageLayoutItem = $items.ListItemAllFields
            $ctx.Load($pageLayoutItem)
        }

        # Get publishing web object
        #
        $web = $ctx.Web
        $pubWeb = [Microsoft.SharePoint.Client.Publishing.PublishingWeb]::GetPublishingWeb($ctx, $web)
        $ctx.Load($pubWeb)

        # Get pages library.
        #
        $pagesList = $ctx.Web.Lists.GetByTitle('Pages')


        # Create page information instance, update properties, 
        # add it, check it in, publish it, and approve it.
        # 
        $pubPageInfo = New-Object Microsoft.SharePoint.Client.Publishing.PublishingPageInformation
        $pubPageInfo.Name = $PageName.Replace(" ", "-") + ".aspx"
        $pubPageInfo.PageLayoutListItem = $pageLayoutItem 
        $pubPage = $pubWeb.AddPublishingpage($pubPageInfo)

        $pubPage.ListItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
        $pubPage.ListItem.File.Publish("")
        $pubPage.ListItem.File.Approve("")

        $ctx.Load($pubPage) 
        $ctx.ExecuteQuery()

        # Page added. Now retrieve list item, check it out, 
        # update title and page content, and check back in.
        #
        $listItem = $pubPage.get_listItem()
        $ctx.Load($listItem)
        $ctx.ExecuteQuery()

        $file = $listItem.File
        $file.CheckOut()
        $ctx.Load($file)
        $ctx.ExecuteQuery()

        $listItem.Set_Item("Title", $PageTitle)
        $listItem.Update()
        $listItem.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
        $listItem.File.Publish("")
        $listItem.File.Approve("")
        $ctx.Load($listItem)
        $ctx.ExecuteQuery()

        Write-Host 'New page ' $PageName ' created successfully' -ForegroundColor Cyan
    }
    catch
    {
        Write-Host ("Error while creating page. Error -->> " + $_.Exception.Message) -ForegroundColor Red
    }

}

Usage:

$credentials = Get-Credential

#Example for page with Custom Page Layout
#
Create-PublishingPage "http://somesite.com" $credentials "Some Page Title" "SomePageName" "YourCustomPageLayout.aspx" $true 

#Example for page with OOB Page Layout
#
Create-PublishingPage "http://somesite.com" $credentials "Some Page Title" "SomePageName" "ArticleLeft.aspx" $false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.