Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Created May 16, 2018 13:04
Show Gist options
  • Save asadrefai/04764db8eb7f3f22212a0e8dd27921a9 to your computer and use it in GitHub Desktop.
Save asadrefai/04764db8eb7f3f22212a0e8dd27921a9 to your computer and use it in GitHub Desktop.
set default page layout in SharePoint using CSOM PowerShell
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 Set-DefaultPageLayout
{
param
(
[string]$url,
[string]$defaultPageLayoutUrl
)
process
{
$Credentials = Get-Credential
#get Client Object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$context.Credentials = $Credentials
#Load objects
$web = $context.Web
$allProps = $web.AllProperties
$context.Load($web)
$context.Load($context.Site.RootWeb)
$context.Load($allProps)
$context.ExecuteQuery()
Write-Host "Setting available page layouts and default page layout on " $web.Url -NoNewLine
$urlRelative = $context.Site.RootWeb.ServerRelativeUrl + "/" + $defaultPageLayoutUrl
if($context.Site.RootWeb.ServerRelativeUrl -eq "/")
{
$urlRelative = $context.Site.RootWeb.ServerRelativeUrl + $defaultPageLayoutUrl
}
$pageLayoutFile = $context.Site.RootWeb.GetFileByServerRelativeUrl($urlRelative)
$context.Load($pageLayoutFile)
$context.ExecuteQuery();
$listItemFields = $pageLayoutFile.ListItemAllFields
$context.Load($listItemFields)
$context.ExecuteQuery()
$pageGuid = $listItemFields.FieldValues["UniqueId"]
$xmlPageLayout = "<layout guid='{0}' url='{1}' />"
$xmlPageLayout = $xmlPageLayout.Replace("{0}", $pageGuid);
$xmlPageLayout = $xmlPageLayout.Replace("{1}", $defaultPageLayoutUrl);
$allProps["__DefaultPageLayout"] = $defaultPageLayoutXml
$web.Update()
$context.ExecuteQuery()
Write-Host " Done" -ForegroundColor Green
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment