Surendra Sharma

Surendra Sharma

Search This Blog

Friday, November 2, 2018

Sitecore PowerShell Script: Change alt value of image items in Sitecore media library


Sitecore PowerShell Script to change media items alt tag with image description or display Name or item name


cls
#input
$mediaTemplateName = "Image"
$mediaParentPath = "master:/sitecore/media library/Project"
$counter = 1

$allMediaItems = Get-ChildItem -Path $MediaParentPath -Recurse
$filteredMediaItems = $allMediaItems | Where-Object { $_.Fields["Alt"].Value -eq "" -and [Sitecore.Data.Managers.TemplateManager]::GetTemplate($_).InheritsFrom("Image") }

foreach($MediaItem in $filteredMediaItems) {
       
        $altValue = $MediaItem.ImageDescription

        if($MediaItem.ImageDescription -eq "" -and $MediaItem.DisplayName -ne "")
        {
            $altValue = $MediaItem.DisplayName.Replace(".jpg", "").Replace(".JPG", "").Replace(".png", "").Replace(".PNG", "").Replace(".gif", "").Replace(".GIF", "")
        }
        elseif($MediaItem.ImageDescription -eq "" -and $MediaItem.Name -ne "")
        {
            $altValue = $MediaItem.Name
        }

        #Update Alt tag
        $MediaItem.Editing.BeginEdit()
        $MediaItem.Fields["Alt"].Value = $altValue
        $MediaItem.Editing.EndEdit()

        Write-Host $counter " -> " $altValue " -> " $MediaItem.ItemPath
        $counter = $counter + 1
}

Any suggestions or improvements are most welcome.

No comments:

Post a Comment