Automating Headless Rendering Variants in SitecoreAI with PowerShell
Hello everyone, Welcome to another blog. Here we will see the magic of Sitecore PowerShell which is useful during Sitecore migration project especially from XP to Sitecore AI.
The problem: dozens of components, several sites, two languages
In a typical multisite SitecoreAI (formerly XM Cloud) solution, sites such as Site1 and Site2 reuse the same set of renderings from a shared Common folder. Each of those renderings needs its own item under the site's Presentation > Headless Variants folder, with at least one Default variant, before authors can use it in Pages.
Doing this by hand means creating dozens of items per site, filling in the Compatible renderings field each time, and then repeating everything in Arabic. It is slow, and it is easy to miss one. So we scripted it.
In this post I'll walk through the script step by step, share the complete version, and add a bonus helper for reading Excel files in PowerShell.
What the script builds
For each rendering in the Common folder, the script creates one Headless Variants item named after the rendering, points it at that rendering, and adds a Default variant underneath:
/sitecore/content/MyTenant/Site1/Presentation/Headless Variants
├── HeroBanner (Headless Variants item, Compatible renderings = HeroBanner rendering ID)
│ └── Default (Variant Definition)
├── PromoCard
│ └── Default
└── ...
These are the IDs and names the script depends on. Check them against your own instance before running it.
| Setting | Value | What it is |
|---|---|---|
$HeadlessVariantsTemplate | {49C111D0-6867-4798-A724-1F103166E6E9} | Template of the per-rendering Headless Variants item |
$VariantDefinitionTemplate | {4D50CDAE-C2D9-4DE8-B080-8F992BFB1B55} | Template of each variant, such as Default |
Rendering template filter | {04646A89-996F-4EE7-878A-FFDBF1F0EF0D} | Template ID used to pick renderings out of the Common folder |
$Compatiblerenderingfield | Compatible renderings | Field that links the variants item to its rendering |
$CommonFolder | /sitecore/layout/Renderings/Project/MyProject/Common | Where the shared renderings live |
$Headlessvariantpath | /sitecore/content/MyTenant/Site1/Presentation/Headless Variants | Target folder for one site |
You run all of this from the PowerShell ISE in SitecoreAI, against the master database.
Step 1: Find every rendering under Common
Start with a dry run that only counts what the script would touch. Get-ChildItem -Recurse walks the Common folder, and Where-Object keeps items on the rendering template while skipping the IDs you list in $excludeIDs.
$lang = "en"
$CommonFolder = "/sitecore/layout/Renderings/Project/MyProject/Common"
# Renderings that should NOT get a headless variant (replace with your own IDs)
$excludeIDs = @(
"{00000000-0000-0000-0000-000000000001}",
"{00000000-0000-0000-0000-000000000002}"
)
$CommonFolderComponent = Get-Item -Path $CommonFolder -Language $lang
$items = Get-ChildItem -Path $CommonFolderComponent.Paths.Path -Recurse |
Where-Object {
$_.TemplateID.ToString() -eq "{04646A89-996F-4EE7-878A-FFDBF1F0EF0D}" -and
$_.ID.ToString() -notin $excludeIDs
}
Write-Host "Renderings to process: $($items.Count)"
# Optional: list them
$items | Select-Object Name, ID | Format-Table
Use the exclusion list for renderings that are not meant to have variants: placeholders, wrappers, or components that already have hand-built variants on the site. The count tells you exactly how many Headless Variants items the next step will create.
Step 2: Create the Headless Variants item and its Default variant
For each rendering found in step 1, the script does three things:
- Creates an item from the Headless Variants template under the site's Headless Variants folder, named after the rendering.
- Writes the rendering's ID into Compatible renderings, appending with a pipe (
|) if the field already has a value, and copies the rendering's display name. - Creates one Variant Definition item called Default under it.
Here is the core of that loop:
foreach ($item in $items) {
$ComponentID = $item.ID
$componentItem = Get-Item -Path $ComponentID -Language $language
# 1. Create the Headless Variants item for this rendering
$newVariantParentItem = New-Item -Name $componentItem.Name `
-ItemType $HeadlessVariantsTemplate `
-Parent $Headlessvariantitem `
-Language $language
# 2. Link it to the rendering via "Compatible renderings"
$current = $newVariantParentItem.Fields[$Compatiblerenderingfield].Value
$newValue = if ([string]::IsNullOrEmpty($current)) { "$ComponentID" } else { "$current|$ComponentID" }
$newVariantParentItem.Editing.BeginEdit()
try {
$newVariantParentItem.Fields[$Compatiblerenderingfield].Value = $newValue
$newVariantParentItem["__Display Name"] = $componentItem.DisplayName
$newVariantParentItem.Editing.EndEdit()
Write-Host "Updated item: $($newVariantParentItem.Paths.FullPath)"
}
catch {
$newVariantParentItem.Editing.CancelEdit()
Write-Error "Failed to update item: $($newVariantParentItem.Paths.FullPath)"
}
# 3. Create the Default variant underneath
foreach ($variantName in $variantNames) {
$newVariant = New-Item -Name $variantName `
-ItemType $VariantDefinitionTemplate `
-Parent $newVariantParentItem `
-Language $language
if ($newVariant) {
Write-Host "Variant '$variantName' created under $($newVariantParentItem.Paths.FullPath)"
}
}
}
A few things worth knowing about this part:
BeginEdit/EndEdit/CancelEditis the standard Sitecore editing pattern. If anything throws inside thetry,CancelEditdiscards the half-finished change instead of leaving the item in an edit state.$variantNamesis an array, so you can create more than one variant per rendering by changing it to, say,@("Default", "Compact").$VariantsRequiredin the full script is a simple on/off switch for the whole block, handy when you only want to re-run the language step.
Step 3: Add Arabic language versions
Our sites run in English and Arabic, and an item with no Arabic version simply does not exist for Arabic pages. So the second half of the script walks everything under the Headless Variants folder and adds an ar version wherever one is missing.
$lang = "ar"
$items = Get-ChildItem -Path $Headlessvariantitem.Paths.Path -Recurse
foreach ($item in $items) {
$sourceItem = Get-Item -Path $item.Paths.Path -Language "en"
$targetItem = Get-Item -Path $item.Paths.Path -Language $lang -ErrorAction SilentlyContinue
if ($null -eq $targetItem -or $targetItem.Versions.Count -eq 0) {
$langData = [Sitecore.Data.Managers.LanguageManager]::GetLanguage($lang)
$database = [Sitecore.Configuration.Factory]::GetDatabase("master")
# Item handle in the target language, then add a version to it
$itemInLang = $database.GetItem($sourceItem.ID, $langData)
$newVersion = [Sitecore.Data.Managers.ItemManager]::AddVersion($itemInLang)
Write-Host "New AR version: $($newVersion.Paths.FullPath) - v$($newVersion.Version.Number)"
}
else {
Write-Host "AR version already exists: $($targetItem.Paths.FullPath)"
}
}
The check on Versions.Count -eq 0 matters: in Sitecore, Get-Item in a language with no version can still return an item object, just with zero versions. Testing only for $null would skip those items.
Because the loop only adds versions where none exist, this part is safe to run again. That is not true of step 2, as the gotchas section below explains.
The full script
This is the combined version: variants first, Arabic versions second. To run it for another site, change $Headlessvariantpath (Site1 and Site2 are both shown) and adjust $excludeIDs. It also skips a rendering whose Headless Variants item already exists, so a second run doesn't create duplicates.
# =====================================================================
# Add a Default headless variant for every Common component,
# then create AR language versions for everything under Headless Variants
# =====================================================================
$CommonFolder = "/sitecore/layout/Renderings/Project/MyProject/Common"
$HeadlessVariantsTemplate = "{49C111D0-6867-4798-A724-1F103166E6E9}"
$VariantDefinitionTemplate = "{4D50CDAE-C2D9-4DE8-B080-8F992BFB1B55}"
$RenderingTemplateID = "{04646A89-996F-4EE7-878A-FFDBF1F0EF0D}"
$Compatiblerenderingfield = "Compatible renderings"
$VariantsRequired = $true
$language = "en" # source language
$lang = "ar" # language to add
# Pick the site
#$Headlessvariantpath = "/sitecore/content/MyTenant/Site1/Presentation/Headless Variants"
$Headlessvariantpath = "/sitecore/content/MyTenant/Site2/Presentation/Headless Variants"
$Headlessvariantitem = Get-Item -Path $Headlessvariantpath -Language $language
$variantNames = @("Default")
# Renderings to skip (replace with your own IDs)
$excludeIDs = @(
"{00000000-0000-0000-0000-000000000001}",
"{00000000-0000-0000-0000-000000000002}",
"{00000000-0000-0000-0000-000000000003}"
)
# ---------- Part 1: Headless variants ----------
$CommonFolderComponent = Get-Item -Path $CommonFolder -Language $language
$items = Get-ChildItem -Path $CommonFolderComponent.Paths.Path -Recurse -Language $language |
Where-Object {
$_.TemplateID.ToString() -eq $RenderingTemplateID -and
$_.ID.ToString() -notin $excludeIDs
}
Write-Host "Renderings found: $($items.Count)"
if ($VariantsRequired -and $Headlessvariantitem) {
foreach ($componentItem in $items) {
$ComponentID = $componentItem.ID.ToString()
$targetPath = "$($Headlessvariantitem.Paths.Path)/$($componentItem.Name)"
# Skip if this rendering already has a Headless Variants item
if (Test-Path -Path "master:$targetPath") {
Write-Host "Skipping, already exists: $targetPath"
continue
}
$newVariantParentItem = New-Item -Name $componentItem.Name `
-ItemType $HeadlessVariantsTemplate `
-Parent $Headlessvariantitem `
-Language $language
$current = $newVariantParentItem.Fields[$Compatiblerenderingfield].Value
$newValue = if ([string]::IsNullOrEmpty($current)) { $ComponentID } else { "$current|$ComponentID" }
$newVariantParentItem.Editing.BeginEdit()
try {
$newVariantParentItem.Fields[$Compatiblerenderingfield].Value = $newValue
$newVariantParentItem["__Display Name"] = $componentItem.DisplayName
$newVariantParentItem.Editing.EndEdit()
Write-Host "Updated item: $($newVariantParentItem.Paths.FullPath)"
}
catch {
$newVariantParentItem.Editing.CancelEdit()
Write-Error "Failed to update item: $($newVariantParentItem.Paths.FullPath)"
}
foreach ($variantName in $variantNames) {
$newVariant = New-Item -Name $variantName `
-ItemType $VariantDefinitionTemplate `
-Parent $newVariantParentItem `
-Language $language
if ($newVariant) {
Write-Host "Variant '$variantName' created under $($newVariantParentItem.Paths.FullPath)"
} else {
Write-Error "Failed to create variant '$variantName'."
}
}
}
}
# ---------- Part 2: Arabic language versions ----------
$langData = [Sitecore.Data.Managers.LanguageManager]::GetLanguage($lang)
$database = [Sitecore.Configuration.Factory]::GetDatabase("master")
$variantItems = Get-ChildItem -Path $Headlessvariantitem.Paths.Path -Recurse
foreach ($item in $variantItems) {
$sourceItem = Get-Item -Path $item.Paths.Path -Language $language
$targetItem = Get-Item -Path $item.Paths.Path -Language $lang -ErrorAction SilentlyContinue
if ($null -eq $targetItem -or $targetItem.Versions.Count -eq 0) {
$itemInLang = $database.GetItem($sourceItem.ID, $langData)
$newVersion = [Sitecore.Data.Managers.ItemManager]::AddVersion($itemInLang)
Write-Host "New AR version: $($newVersion.Paths.FullPath) - v$($newVersion.Version.Number)"
}
else {
Write-Host "AR version already exists: $($targetItem.Paths.FullPath)"
}
}
Bonus: Read an Excel file from the Media Library
A natural next step is to make the component list dynamic: keep it in an Excel file in the Media Library and read it from SPE.
SitecoreAI doesn't let you install modules like ImportExcel on the CM, but you don't need them. An .xlsx file is a zip package of XML parts, and .NET's System.IO.Packaging (in WindowsBase) can open it directly. The function below reads the first sheet and returns one PowerShell object per row, using the header row for property names.
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
Write-Host "[$Level] $Message"
}
# "C12" -> 2 (zero-based column index)
function Get-ColumnIndex {
param([string]$CellRef)
$letters = ($CellRef -replace '\d', '').ToUpper()
$index = 0
foreach ($ch in $letters.ToCharArray()) {
$index = ($index * 26) + ([int]$ch - [int][char]'A' + 1)
}
return $index - 1
}
function Read-ExcelFromStream {
param([System.IO.Stream]$Stream)
Add-Type -AssemblyName WindowsBase
Write-Log "Reading Excel package..."
$package = [System.IO.Packaging.Package]::Open($Stream, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
try {
# Shared strings: most text cells point into this table
$sharedStrings = @()
$ssUri = New-Object System.Uri("/xl/sharedStrings.xml", [System.UriKind]::Relative)
if ($package.PartExists($ssUri)) {
$reader = New-Object System.IO.StreamReader($package.GetPart($ssUri).GetStream())
$ssXml = [xml]$reader.ReadToEnd()
$reader.Close()
foreach ($si in $ssXml.sst.si) {
# Plain text sits in <t>; rich text is split across <r><t> runs
$sharedStrings += ($si.SelectNodes(".//*[local-name()='t']") | ForEach-Object { $_.InnerText }) -join ''
}
}
else {
Write-Log "No shared strings found" "WARNING"
}
# First worksheet
$sheetUri = New-Object System.Uri("/xl/worksheets/sheet1.xml", [System.UriKind]::Relative)
$reader = New-Object System.IO.StreamReader($package.GetPart($sheetUri).GetStream())
$xml = [xml]$reader.ReadToEnd()
$reader.Close()
}
finally {
$package.Close()
}
Write-Log "Parsing Excel data..."
$rows = New-Object System.Collections.Generic.List[hashtable]
foreach ($row in $xml.worksheet.sheetData.row) {
$values = @{}
foreach ($c in $row.c) {
$col = Get-ColumnIndex $c.r # empty cells are omitted, so use the cell reference
$values[$col] = switch ($c.t) {
"s" { $sharedStrings[[int]$c.v] }
"inlineStr" { $c.is.InnerText }
default { $c.v } # numbers, booleans, formula results
}
}
$rows.Add($values)
}
if ($rows.Count -eq 0) { return @() }
# Header row -> property names
$header = $rows[0]
$maxCol = ($header.Keys | Measure-Object -Maximum).Maximum
$data = foreach ($r in ($rows | Select-Object -Skip 1)) {
$obj = [ordered]@{}
for ($i = 0; $i -le $maxCol; $i++) {
$name = if ($header[$i]) { $header[$i] } else { "Column$($i + 1)" }
$obj[$name] = $r[$i]
}
[PSCustomObject]$obj
}
Write-Log "Parsed $(@($data).Count) data rows"
return $data
}
To use it with a file in the Media Library, open the media item's blob and copy it into a MemoryStream first, because Package.Open needs a seekable stream:
# Example path - point this at your own upload
$mediaPath = "master:/sitecore/media library/Project/MyProject/Imports/headless-variants.xlsx"
$mediaItem = [Sitecore.Data.Items.MediaItem](Get-Item -Path $mediaPath)
$blob = $mediaItem.GetMediaStream()
$ms = New-Object System.IO.MemoryStream
$blob.CopyTo($ms)
$blob.Close()
$ms.Position = 0
$data = Read-ExcelFromStream -Stream $ms
$ms.Dispose()
$data | Format-Table
From there you can drive the variant script from the spreadsheet. For example, with a sheet that has RenderingID and CreateVariant columns:
$excludeIDs = $data |
Where-Object { $_.CreateVariant -eq "No" } |
ForEach-Object { $_.RenderingID }
Two limits to keep in mind. The function reads sheet1.xml, which is usually, but not always, the first tab. And Excel stores dates as serial numbers, so convert them with [DateTime]::FromOADate([double]$value).
Gotchas and lessons learned
- Step 2 isn't idempotent on its own.
New-Itemdoesn't stop if an item with the same name exists. It creates a sibling. Without theTest-Pathguard in the full script, running twice gives you two "HeroBanner" items, each with its own Default variant. - Arabic versions start empty.
AddVersioncreates a blank version. Shared fields, such as Compatible renderings if it is marked Shared on its template, carry over, but language-specific fields don't, so__Display Nameis empty in Arabic until someone fills it in. Set it in the same loop if you have the Arabic names, for example from the Excel sheet. - Always do a count first. Run the step 1 snippet and check
$items.Countbefore creating anything. If the number looks wrong, your template ID filter or exclusion list is off. - Serialize or back up first. Run it on a non-production environment, then move the items with your usual serialization (Sitecore CLI) or a package, so the change is reviewable and repeatable.
- Publish afterwards. The script writes to master only. Publish the Headless Variants folder, in both languages, before checking the result on the site.
- Undoing a run. Every item the script creates sits under one folder, so cleanup is easy: delete the newly created children of Headless Variants, or restore them from the Recycle Bin.
Wrapping up
With one script, setting up headless variants for a new site drops from an afternoon of clicking to a single run. Point it at the site's Headless Variants folder, check the count, run it, and publish in both languages.
The same pattern works for most bulk setup jobs in SitecoreAI: find items with Get-ChildItem and a template filter, create items with New-Item, edit inside BeginEdit/EndEdit, and add language versions with ItemManager.AddVersion. Add the Excel reader and the whole job can be driven by a spreadsheet your content team maintains.
If you use this on your own project, let me know in the comments what you changed. Keep learning and keep sharing!!
You can check my other blogs too if interested. Blog Website
Comments
Post a Comment