Change layout Sitecore Powershell Extensions script

Today I got a request to update thousands of items' layouts. The requirement arose because the solution was using around 6 layouts and we all know that a good practice is to have the least number of layouts possible (1 per device is recommended). We ended up combining those layouts and we needed to update the presentation details of the existing items.

In order to do this, I created the following SPE script which updates all the items' layouts starting from the specified root path: 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
$rootItem = Get-Item -Path master:"PATH TO ROOT"
$newLayout = Get-Item -Path master:"NEW LAYOUT PATH"
$oldLayout = Get-Item -Path master:"OLD LAYOUT PATH"
$defaultDevice = Get-LayoutDevice "Default"
# True: Update Final Layout - False: Update Shared Layout
$useFinalLayout = $False
# True: Informative only - False: Update Items
$reportOnly = $False
foreach ( $item in Get-ChildItem -Item $rootItem -Recurse )
{
    $layout =  Get-Layout -Item $item -Device $defaultDevice -FinalLayout:$useFinalLayout
    if ($layout -And $layout.ID -match $oldLayout.ID )
    {
  if(!$reportOnly){
   Set-Layout -Item $item -Device $defaultDevice -Layout $newLayout -FinalLayout:$useFinalLayout
  }
  Write-Host "$($item.FullPath)  --> Old Layout: $($layout.Name)   --> New Layout: $($newLayout.Name)"
    }
}

This SPE script lets you specify the following parameters:

  • Root Item - The initial point where we are going to start updating items. 
  • New Layout - The path of the new layout. 
  • Old Layout - The path of the old layout. 
  • Default Device - The device this layout will be changed for (Default, Print, Feed, etc).
  • Use Final Layout - Set it to true to update the final layout and false to update the shared layout
  • Report Only - This is a flag that when set to true will only print the items that will be changed without actually updating the items.
Template changes should happen at the standard values level, however, there might be some cases where you want to update the content items directly. 

Happy item updating! 

Comments