- Published on
Haciendo uso de SPE para archivar contenido no referenciado en la media library y en el directorio de SXA data
- Authors
- Name
- Francisco Caicedo Narvaez
- @_Francisco_CN
Con el pasar de los años, el árbol de contenido en Sitecore crece y se comienza a acumular de contenido que ya no es necesario. Buscando la manera de optimizar el árbol de contenido, he preparado un script hecho en PowerShell que permite encontrar contenido de la media library o, en el caso de que el proyecto utilice SXA, contenido existente en el directorio de SXA data que ya no está referenciado en el proyecto. Permitiendo visualizar y archivar en forma masiva los resultados encontrados.
Visualizar y/o Archivar contenido no referenciado
Este script fie creado para visualizar y archivar contenido de la media library como también del directorio de SXA data. Este último aplica en proyectos que usa SXA.
Después de ejecutar el siguiente script, los resultados muestran contenido de la media library ubicado en directorios pertenecientes a <project_name> que no están referenciados en el árbol de contenido. Como también contenido ubicado en /sitecore/content/<project_name>/Data.
Antes de ejecutar el script, se debe reemplazar <project_name> con el nombre del proyecto.
$options = @{
"Media Items"= "media"
"<project_name> Data"= "projectdata"
}
$props = @{
Title = "Preview and/or Archive items"
Description = "Displays items not referenced that can be archived"
OkButtonName = "Run Report"
CancelButtonName = "Cancel"
Parameters = @(
@{ Name = "selectedOption"; Title = "Select Search Location"; Options = $options; Tooltip = "Choose one option" },
@{ Name = "performArchiving"; Title = "Archiving enabled"; Value=$false; Tooltip = "Check to perform archiving" }
)
}
$result = Read-Variable @props
if($result -ne "ok") {
Close-Window
Exit
}
# 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
}
# ArchiveItem archives Sitecore item passed as param
function ArchiveItem {
param(
$Item
)
if($performArchiving -eq $true) {
$archive = [Sitecore.Data.Archiving.ArchiveManager]::GetArchive("archive", $Item.Database)
$archive.ArchiveItem($item)
Write-Host "Item archived: " $Item.ItemPath
}
}
function Get-Items {
switch($selectedOption) {
"media" {
Get-MediaItemWithNoReference
}
"projectdata" {
Get-ProjectDataWithNoReference
}
default {
Write-Host "Not available."
Close-Window
Exit
}
}
}
function ProcessItems {
param(
$Items,
[bool]$checkHelixFolders = $false
)
foreach($item in $Items) {
if($checkHelixFolders) {
$projectItem = $item.ItemPath | %{$_ -match "Feature/<project_Name>/" -or $_ -match "Foundation/<project_Name>/" -or $_ -match "Project/<project_Name>/"}
if($projectItem -contains $true) {
if(!(HasReference($item))) {
$item
ArchiveItem($item)
}
}
} else {
<#
Exclusions list for SXA default Data items.
SXA Forms: {7F9D1A45-F31E-4714-AC66-1E300AE1B792}
SXA Gallery: {57BCF1CE-35CB-4752-B23B-2D4522AF6292}
SXA POIs: {8CA8B80D-A1AD-4B45-9F08-8839357E71D4} and {7DD9ECE5-9461-498D-8721-7CBEA8111B5E}
SXA Security: {33077D51-EBAD-4D1C-B4A8-3B79F51DBA13}
SXA Carousel: {ADD22F05-6B4C-4344-95AD-9A1A9BA6A216}
...
Add more as required
#>
$itemExclusions = @(
"{7F9D1A45-F31E-4714-AC66-1E300AE1B792}",
"{57BCF1CE-35CB-4752-B23B-2D4522AF6292}",
"{8CA8B80D-A1AD-4B45-9F08-8839357E71D4}",
"{7DD9ECE5-9461-498D-8721-7CBEA8111B5E}",
"{33077D51-EBAD-4D1C-B4A8-3B79F51DBA13}",
"{ADD22F05-6B4C-4344-95AD-9A1A9BA6A216}"
)
if($itemExclusions -notcontains $item.TemplateID) {
Write-Host $item.Template.FullName
if(!(HasReference($item))) {
$item
ArchiveItem($item)
}
}
}
}
}
<#
Gets all the items in the media library
and checks to see if they have references.
#>
function Get-MediaItemWithNoReference {
$items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse |
Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
ProcessItems -Items $items -checkHelixFolders $true
}
<#
Gets all the items under Project Data folder (SXA only)
and checks to see if they have references.
#>
function Get-ProjectDataWithNoReference {
$items = Get-ChildItem -Path "master:\sitecore\content\<project_name>\Data" -Recurse |
Where-Object { $_.TemplateID -ne "{A87A00B1-E6DB-45AB-8B54-636FEC3B5523}"} # Exclude Common Folders; /sitecore/templates/Common/Folder
ProcessItems -Items $items
}
$props = @{
InfoTitle = "Non referenced items"
InfoDescription = "Lists all media or data items that are not linked to other items."
PageSize = 50
}
# Call Show-ListView to produce a table with the results.
Get-Items |
Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Path"; Expression={$_.ItemPath} },
@{Label="Template"; Expression={$_.TemplateName} },
@{Label="TemplatePath"; Expression={$_.Template.FullName} },
@{Label="TemplateID"; Expression={$_.TemplateID} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} }
Close-Window
Al momento de ejecutar el reporte, es presentada la opción de escoger entre la media library y el directorio SXA data como la raíz en donde se realizará la búsqueda.
También existe una opción que permite seleccionar entre archivar o únicamente visualizar los resultados. La opción por defecto es visualizar únicamente.

Los resultados mostraran el contenido que puede ser archivado. Estos resultados serán archivados cuando el reporte es generado únicamente si la opción “Archiving enabled" es seleccionada en el paso anterior.

Cuando la función ArchiveItem($item) es ejecutada, todo el contenido encontrado al momento de generar el reporte será movido al Sitecore Archive.


Borrando contenido que no está siendo usado en el proyecto periódicamente ayudara con el rendimiento de la indexación, reduciendo el tiempo de carga cuando se usa el Experience Editor y también cuando se abre la ventana flotante para seleccionar contenido de la media library.