How to Find and Delete Unreferenced Items in Sitecore
Overview
A quick example of PowerShell script to find orphaned items in Media Library (to which no other item is pointing to).
Getting Started
Here's the situation I saw on multiple projects with multiple clients: Sitecore Media Library would grow quite large over time, maintained by different teams and users, which eventually lead to the situation where some of those items are no longer used or needed, but continue to stay there. One way to identify such 'orphans' is to find those, not used by any other item in the Sitecore content tree. Finding all items, pointing to one given item is easy with Sitecore content editor:
But what if we need to find hundreds or even thousands of such 'orphan' items? I wrote a quick PowerShell script to find such orphans in Media Library, ended up using it more than once, so this may be useful for others...
Disclaimer
This script is just an example and needs to be used with extra caution, especially on PROD environments: don't hold me responsible for accidental deletion of data in YOUR instance :)
PowerShell Script to Find and Delete Unused Items in Sitecore
# Root path to look 'orphan' items under - update here as needed
cd 'master:/sitecore/media library/add your root path here'
# Look for items by template name - update as needed
# To search for everything except, say, a Media Folder condition may look like this: Where-Object { $_.TemplateName -me 'Media Folder' }
$itemsToProcess = Get-ChildItem -Recurse . | Where-Object { $_.TemplateName -eq 'Image' }
if ($itemsToProcess -ne $null) {
$itemsToProcess | ForEach-Object {
$referrers = Get-ItemReferrer -Item $_ | measure
if ($referrers.Count -gt 0) {
Write-Host $_.ID 'has referrers'
} else {
Write-Host $_.ID 'no referrers'
# I commented this out just in case someone run this accidentally. I suggest to test run and check log output before uncommenting the following line
# $_ | Remove-Item;
}
}
}