Execute Sitecore code in PowerShell

As I was working on an upgrade from 9.3 to 10.1, I came across an issue where, while running in local docker containers, I couldn’t resolve a site as I had once done on 9.3. The ultimate solution was related to traefik labels, compose files, and docker magic, however, the troubleshooting process led me to something I thought others might find helpful.

We had multiple site definitions, using various forms of the Valid For Environment field on the site defintion. When deployed to azure, everything worked just fine. Naturally.

For example:

Being 10.1, I wondered if it was some sort of change in the SXA Site Resolver. I could have written some custom code to insert into a pipeline somewhere and set a break point, but honestly I was too lazy to be bothered. I figured there had to be a way to execute the code, just to see the output… Being proficient, but not quite the powershell guru that is Michael West, off to google I went.

In this case, I was really only concerned with what sites were resolved, given the environment, just to make sure things hadn’t changed that much between 9.3 and 10.1… Luckily, the code I needed just happened to be exposed through a PUBLIC interface AND was registered with the DI container!


So, how about some powershell?

# Get the instance of the type I need from the DI container
$environmentSiteResolverType = [Sitecore.XA.Foundation.Multisite.SiteResolvers.IEnvironmentSitesResolver]
$environmentSiteResolver = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider.GetService($environmentSiteResolverType) -as $environmentSiteResolverType

# Get the `Sites` item at /sitecore/system/Settings/Foundation/Experience Accelerator/Multisite/Management/Sites
$sitesItem = Get-Item -path master: -id "{F78EC6BE-D9BA-4595-B740-E801ACDB0459}"
$sitesArray = $sitesItem.Fields["Order"].Value.Split("|")

# Create the `List<Item>` needed to pass in to the method
$siteItems = New-Object System.Collections.Generic.List[Sitecore.Data.Items.Item]

foreach($id in $sitesArray) {
    $item = Get-Item -path master: -id $id

# Execute the Sitecore code
$environmentSiteResolver.ResolveEnvironmentSites($siteItems, "Local")

Write-Host "PROFIT!!"

The Proof

Not revolutionary, but hope someone finds this helpful!

Happy Sitecore trails, my friend!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: