This feature is one of my most favourite things that Sitecore Powershell Extensions has to offer. We can use Sitecore Powershell scripts as the field source for our template fields, when Sitecore queries do not help.
In this article, I explain how you can use a Sitecore Powershell script as the field source for your template fields.
Sitecore queries are often enough for templates used to build simple components. But, there are times when we need some logic to be performed to show the field source. We can use Sitecore queries to filter out the datasources based on the template name, template id etc. But, what if the logic is more complicated? You can also build something custom, as mentioned in this article: Sitecore Source Field Code: query that implements IDataSource.
We can use Sitecore Powershell Scripts instead for the following reasons:
For this article, I will use an example where I needed a list of the root items of SXA Sites for a droplink field.
$database = [Sitecore.Configuration.Factory]::GetDatabase("master")
$SiteResolver = [System.Type]([Sitecore.XA.Foundation.Multisite.ISiteInfoResolver])
$sites = [Sitecore.DependencyInjection.ServiceLocator]::get_ServiceProvider().GetService($SiteResolver).Sites | ForEach-Object { $database.GetItem($_.RootPath) } | `
Where-Object { $_ -ne $null -and $_.ID -ne $null} | Sort-Object -Unique
return $sites
Happy Sitecoring!