
Sitecore PowerShell: A PowerShell script to fix broken renderings in Content Pages

I am a Senior production support developer at Velir. I Specialize in Sitecore technologies in the production support department.
One of my clients reported an issue that when they try to edit and then save a page in the Sitecore content tree, they get an error message saying that the page contains broken links in the final renderings field.

Some of the renderings in the branch template were pointing to the wrong data source. So with every new page they create they get this error message upon saving the page. I fixed the datasource in the branch template but the problem is that they had already created a lot of pages before fixing the branch template.
Fixing the existing pages
To fix the existing pages, I created a Sitecore PowerShell script to iterate over the pages and check for broken/Invalid links in the data source field of every rendering on the page.
The script:
- We had thousands of pages in the content with broken final renderings so I used the sitecore master index in the query instead of running a regular sitecore query (line 1)
- I applied 2 filters. one for the template and the other one is the start location of the search. You can tweak these based on what content is affected (line 5 and 10).
- Iterate over all the renderings and check if the datasource is valid. if getting the dataource item returned null then I replace the dataource field in the rendering with an empty/null value (line25).
- $count variable is just to display how many renderings have been fixed after completing running the script.
$results = Find-Item -Index sitecore_master_index -Criteria @(
@{
Filter = "Equals";
Field = "_templatename";
Value = "Detail Page" #Specify the template name here
}
@{
Filter = "StartsWith";
Field = "_fullpath";
Value = "/sitecore/content"} #specify the start location here
) | Initialize-Item
$count =0;
$results | ForEach-Object {
$renderingInstance = Get-Rendering -Item $_ -FinalLayout -Rendering $rendering
for($i=0; $i -lt $renderingInstance.Length; $i++){
$currentID = $renderingInstance[$i].datasource
if($currentID){
$currentItem = Get-Item -Path master: -ID $currentID
if(!$currentItem){
$count++;
$renderingInstance[$i].datasource = $null
Set-Rendering -Item $_ -Instance $renderingInstance[$i] -FinalLayout
}
}
}
}
Write-Host $count