Sitecore PowerShell Script to delete unused items in the Media Library

esdanielgomez

Daniel Gomez

Posted on March 26, 2024

Sitecore PowerShell Script to delete unused items in the Media Library

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



Enter fullscreen mode Exit fullscreen mode

Example:

This is an example of an unused image that can be removed using the script:

Run the PowerShell 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.

X / LinkedIn - esdanielgomez.com

💖 💪 🙅 🚩
esdanielgomez
Daniel Gomez

Posted on March 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related