Created
July 27, 2022 02:16
-
-
Save KKings/3cfe8be06d9ed8ad0c0dfa62de3878ab to your computer and use it in GitHub Desktop.
Sitecore Powershell Script to remove orphan renderings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$items = gci . -Recurse | |
Foreach($item in $items) { | |
$allRenderings = Get-Rendering -Item $item -FinalLayout | |
$dynamicRenderings = $allRenderings | Where-Object {$_.Placeholder -match '(-{[0-9a-fA-F]{8}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{12}}-0)'} | |
$regexOptions = ([System.Text.RegularExpressions.RegexOptions]::MultiLine -bor [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) | |
$regex = new-object regex('{[0-9a-fA-F]{8}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{12}}', $regexOptions) | |
$results = New-Object System.Collections.Generic.List[Sitecore.Layouts.RenderingDefinition] | |
Foreach($rendering in $dynamicRenderings) { | |
$matches = $regex.Matches($rendering.Placeholder) | |
if ($matches.Length -eq 0) { | |
return; | |
} | |
Foreach($match in $matches) { | |
$id = [Sitecore.Data.ID]::Parse($match.Value) | |
$isFound = ($allRenderings | Where-Object { $_.UniqueID -eq $id } ).Count -gt 0 | |
if (!$isFound) { | |
$results.Add($rendering); | |
break; | |
} | |
} | |
} | |
#Write-Host "Found $($results.Count) results for ..." | |
$device = (Get-LayoutDevice "Default") | |
Foreach($result in $results) { | |
$renderingItem = gi -Path 'master:' -ID $result.ItemID | |
Write-Host "Removing $($renderingItem.DisplayName) with $($result.UniqueID) from $($item.Name)-$($item.ID)" | |
$item | Remove-Rendering -Instance $result -FinalLayout -Language 'en-US' -Device $device | |
} | |
} |
Why are you setting the regexOption IgnoreCase on line 8, and test for [a-fA-F] the line below?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If Content Authors have the ability to remove top-level renderings that contain placeholders, they will create orphan renderings if they do not remove all renderings within the placeholder before removing the top-level rendering.
This example script removes those renderings that no longer render.