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 changed on Google or on ChatGPT.
Therefore, I conducted quick research and created a script that can be useful for others as well.
The PowerShell script below can be used to change a variant for a rendering in Sitecore.
Let's get it indexed in search 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
}
Conclusion
With the help of PowerShell scripting, you can modify rendering variants in Sitecore to create personalized web designs. This can enhance the user experience and help tailor your website to meet specific business needs. Learning how to use PowerShell script is a great way to empower yourself with the tools to create a website that truly stands out. Reach out to us with any queries or concerns that you may have and be sure to receive consultation and implementation from our certified experts.
Publications
& Thought Leadership


