powershell update

ok
02 Mar, 24
Sitecore

# Specify the old and new rendering IDs

$oldRenderingId = "{OLD-RENDERING-ID}"

$newRenderingId = "{NEW-RENDERING-ID}"


# Define the path to search for items, e.g., "/sitecore/content/Home"

$startPath = "master:/sitecore/content"


# Fetch items under the specified path

$items = Get-ChildItem -Path $startPath -Recurse


foreach ($item in $items) {

    # The field ID for the Final Renderings is "{04BF00DB-F5FB-41F7-8AB7-22408372A981}"

    $finalRenderingsField = $item.Fields["__Final Renderings"]


    if ($finalRenderingsField -and $finalRenderingsField.HasValue) {

        $layoutXml = [Sitecore.Layouts.LayoutDefinition]::Parse($finalRenderingsField.Value)

        $deviceLayout = $layoutXml.Devices | ForEach-Object {

            $hasChanges = $false


            # Iterate through all renderings for the device

            $_.Renderings.Renderings | ForEach-Object {

                if ($_.ItemID -eq $oldRenderingId) {

                    # Capture the original properties

                    $originalDatasource = $_.Datasource

                    $originalParameters = $_.Parameters

                    $originalPlaceholder = $_.Placeholder


                    # Update to the new rendering

                    $_.ItemID = $newRenderingId

                    $_.Datasource = $originalDatasource

                    $_.Parameters = $originalParameters

                    $_.Placeholder = $originalPlaceholder


                    $hasChanges = $true

                }

            }


            if ($hasChanges) {

                # Apply changes if any rendering was updated

                $item.Editing.BeginEdit()

                $finalRenderingsField.Value = $layoutXml.ToXml()

                $item.Editing.EndEdit()

                Write-Host "Updated rendering for item: $($item.Paths.Path)"

            }

        }

    }

}