Wednesday, December 22, 2021

Sitecore PowerShell script to remove all language versions except one

This post provides Sitecore PowerShell script to remove all lang versions except one for items under a Sitecore node recursively.

Here in my example, removes all language versions except for English language.

In some cases you may want to remove versions of an item or an entire node in all languages except one or few languages. In that case it is difficult to remove them manually. Instead if we can use a PowerShell script in Sitecore, it would make our job very easy.

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

Steps:

  1. Retrieve all the child items recursively. Include the root item too.
  2. For each item, get all the versions in all languages.
  3. Check if the language version retrieved is the one you want to remove.If so, use the Remove-ItemVersion to remove that particular version.

With versions

Versions deleted

Sitecore PowerShell script

$props = @{
   InfoTitle = "Remove Versions"
    PageSize = 10000000
}

$sourcePath =  "master:/sitecore/content/Home/Site1"

function Remove-Versions {

    $items = Get-ChildItem -Path $sourcePath -Recurse
    $rootItem = Get-Item -Path $sourcePath
    $items = $items + $rootItem

    foreach ($item in $items)
    {
        foreach ($version in $item.Versions.GetVersions($true))
        {
            if ($version.Language -ne "en")
            {
                Remove-ItemVersion $version
                Write-Host $version.ID " - " $version.Language "- deleted"
                $version;
            }
        }   
    }

}

$items = Remove-Versions
$items | Show-ListView @props -Property ItemPath, ID, @{Label="Language"; Expression={$_."Language"}} 
Close-Window