Thursday, April 13, 2023

Using PowerShell to Change Sitecore SXA Rendering Variants

Recently, while working on a POC for a client, I faced a challenge to change SXA variants for renderings in bulk. 

As a solution, I decided to create a PowerShell script for it.

Although I hadn't performed this particular task in the past and I couldn't find the exact field that needs to be change on Google or on ChatGPT. 

Therefore, I conducted quick research and created a script that can be useful for others as well.


The below PowerShell script can be used to change a variant for a rendering in Sitecore.

Lets get it indexed in serch engines :)


        
$renderingFolder = Get-Item -Path "master:/sitecore/layout/Renderings/Feature/YourProjectFolder"
$renderingVariantsFolder = Get-Item -Path "master:/sitecore/content/YourProjectFolder/YourProjectFolder/Presentation/Rendering Variants"
$defaultLayout = Get-LayoutDevice -Default

$itemPath = "/sitecore/content/NTTDataAmerica/NTTDataAmerica/Home/YourPage"
$renderingName = "Your rendering name"
$variantName = "Your variant to apply"

# Get the page item
$item = Get-Item -Path $itemPath 

# Find the item with the specified rendering name
$rendering = Get-ChildItem -Path $renderingFolder.FullPath -Recurse | Where-Object { $_.Name -eq $renderingName }
$renderingInstances = Get-Rendering -Item $item -Rendering $rendering -Device $defaultLayout -FinalLayout

# Find the item with the specified variant name	
$renderingVariants = Get-ChildItem -Path $renderingVariantsFolder.FullPath -Recurse | Where-Object { $_.Name -eq $renderingName }
$newVarient = Get-ChildItem -Path $renderingVariants.FullPath -Recurse | Where-Object { $_.Name -eq $variantName }

#there can be more then 1 rendering on a page
foreach ($renderingInstance in $renderingInstances) {

    #rendering Variants stored in "FieldNames"
	$renderingParameters = [ordered]@{"FieldNames"=$newVarient.ID}
		
	# Save the changes to the rendering instance
	Set-Rendering -Item $item -Instance $renderingInstance -Parameter $renderingParameters -FinalLayout
		
}
        
    

No comments:

Post a Comment