Sitecore PowerShell script to get unreferenced media items

Pranay    20 May '19    404 views

This PowerShell script can be used to clean or list all the Sitecore media library items which are not referenced by any item in Sitecore. This can also be restricted to a sub tree within the media library by updating the source path accordingly.

To run this script it requires the Sitecore PowerShell module to be installed on your Sitecore instance.

Is this not the script you are looking for? Then check the complete list of Sitecore Powershell scripts

Image Text

Steps:

  1. Retrieve all the child items recursively from the media library root node \sitecore\media library. If you want to check only from a subtree/folder inside the media library, then update this path in the script below accordingly.
  2. For each media item, get the count of items which have references to this media item.
  3. If the count of references is zero, then consider this to be an unreferenced media item.
  4. Display all such items in a tabular format using the Show-ListView of PowerShell.

Sitecore PowerShell script to get unreferenced media items

function HasReference {
    param(
        $Item           
    )    
    $linkDb = [Sitecore.Globals]::LinkDatabase
    $linkDb.GetReferrerCount($Item) -gt 0
}
function Get-MediaItems {
    $items = Get-ChildItem -Path "web:\sitecore\media library" -Recurse | 
        Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
    foreach($item in $items) {
        if(!(HasReference($item)) ) {
            $item
        }
    }
}
$props = @{
    InfoTitle = "Media items without references"
    InfoDescription = "Media items without references"
    PageSize = 100000
}

Get-MediaItems |
    Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
        @{Label="File Type"; Expression={$_.Extension} },
        @{Label="Path"; Expression={$_.ItemPath} }

About the author

Pranay Deegoju
Sitecore Certified Professional

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.



Leave your comments on this post here


Want more such posts, subscribe here

Recent Posts

×

Liked this article?

Subscribe with your email and get updates when ever a new article is posted.

By subscribing you agree to our privacy terms. We promise that we do not sell your data.