Hi! In this blog, we will find a Sitecore PowerShell script to be able to eliminate multimedia elements that are not being used.
The general idea is to analyze the items or children of a specific path and verify that those items don't have any references. If the item has no reference, then it will be deleted.
Sitecore PowerShell Script
$mediaLibraryRootPath = "master:/sitecore/media library"
# HasReference determines if the specified item is referenced by any other item.
function HasReference {
param(
$Item
)
$linkDb = [Sitecore.Globals]::LinkDatabase
$linkDb.GetReferrerCount($Item) -gt 0
}
# Get-MediaItemWithNoReference gets all the items in the media library and checks if they have references. If the item has no reference, the media item is saved locally and then deleted.
function Get-MediaItemWithNoReference {
$items = Get-ChildItem -Path $mediaLibraryRootPath -Recurse |
Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
$i = 0
foreach($item in $items) {
if(!(HasReference($item))) {
$i = $i + 1
Write-Output "$($i). $($item.ItemPath)"
$item | Remove-Item
}
}
}
# Run the script.
Write-Output "Items to delete:"
Get-MediaItemWithNoReference
Example
This is an example of an unused image that can be removed using the script:
Thanks for reading!
I hope this script has been useful to you. If you have any questions or ideas in mind, it'll be a pleasure to be able to be in communication with you, and together exchange knowledge with each other.