Monday, April 4, 2022

Powershell script to search a keyword in all items in Sitecore

This Powershell script is used to search for an occurrence of a string in all Sitecore items and in all the fields, including the standard fields.

The script traverse through all the items under the item path provided in the script. For each item, it gets all the fields and in each field it tries to match the input string. If the input matches then that item along with additional details is added to an ArrayList which is displayed at the end.

Powershell script to search for a pattern in Sitecore

Note: As the script goes through each item and all its fields, this script would take time to run. It is suggested not to run on the entire site root, instead run it on the sections needed.

Powershell script

$startPath = "master:/sitecore/content/Site1"
Write-Host "Search started $(Get-Date -format 'u')"
$list = [System.Collections.ArrayList]@()
$itemsToProcess = Get-ChildItem $startPath -Language * -Recurse
if($itemsToProcess -ne $null) {
    $itemsToProcess | ForEach-Object { 
        $match = 0;
        foreach($field in $_.Fields) {
                if($field -match '.*productName.*') {
                    $info = [PSCustomObject]@{
                        "ID"=$_.Paths.FullPath
                        "Language"=$_.Language
                        "TemplateName"=$_.TemplateName
                        "FieldName"=$field.Name
                        "FieldType"=$field.Type
                        "FieldValue"=$field
                    }
                    [void]$list.Add($info)
            }
        }
    }
}
Write-Host "Search ended $(Get-Date -format 'u')"
Write-Host "Items found: $($list.Count)"
$list | Format-Table

Hope it helps. Please do share!!

No comments:

Post a Comment