Sitecore Powershell: Remove all items that are not referenced by others

Sitecore Powershell

This script will scan children of root (currently set too \sitecore\media library ) and return any items that are not references by other content items (using the links DB - this needs to be up-to-date to work correctly). As a safety measure, it will also exclude an item if it has children.

To use this script:

  1. Set root by replacing \sitecore\media library
  2. Optionally recurse through all children and children etc by adding -Recurse to line 27:

    $items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse |
  3. Run this script initially to see what is returned in the hash table.
  4. Replace line 48 (where it says $item nested in the middle of Get-MediaItemWithNoReference) with the following when you want to execute the operation:

    Get-MediaItemWithNoReference | Remove-Item

Note: One thing to consider is that items may exist to be downloaded, but not actually references by an item. In this situation, we asked all authors to move such items to a download folder (and excluded that from the action).

# 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
}

function HasChildren($item)
{
    $contOfImages = 0
    $children = $item.Children
    foreach($chItem in $children){
            $contOfImages++
    }
    $contOfImages -gt 0
}

<# 
    Get-MediaItemWithNoReference gets all the items in the media library
    and checks to see if they have references. Each item that does not
    have a reference is passed down the PowerShell pipeline.
#>
function Get-MediaItemWithNoReference {
    $items = Get-ChildItem -Path "master:\sitecore\media library" | 
        Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
    
    foreach($item in $items) {
        if(!(HasReference($item))) {
            if(!(HasChildren($item))) {
                $item
            }
        }
    }
}

# Setup a hashtable to make a more readable script.
$props = @{
    InfoTitle = "Unused media items"
    InfoDescription = "Lists all media items that are not linked to other items."
    PageSize = 25
}

# Passing a hashtable to a command is called splatting. Call Show-ListView to produce
# a table with the results.
 Get-MediaItemWithNoReference | 
    Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
        @{Label="Updated"; Expression={$_.__Updated} },
        @{Label="Updated by"; Expression={$_."__Updated by"} },
        @{Label="Created"; Expression={$_.__Created} },
        @{Label="Created by"; Expression={$_."__Created by"} },
        @{Label="Path"; Expression={$_.ItemPath} }
        
Close-Window

Leave a Reply

Your email address will not be published. Required fields are marked *