The last post I wrote in this series - Sitecore Powershell Extensions Example Scripts was very well-received.
So, here I am with more scripts examples. I will continue posting more and more in this series as I write more scripts.
This article has methods to retrieve Sites, Languages in a Sitecore instance,
Sitecore Powershell Extensions a.k.a SPE is one of my favorite modules for Sitecore. You can automate/build tools for most tasks you face as a Sitecore Developer. You can read more about SPE here.
The scripts that I have posted below can be pasted and directly executed on the Powershell ISE provided by SPE.
Please modify the variables as per your requirement before executing them.
This snippet can be used to get the Sitecore sites from the Sitecore configuration. Some of the situations where this can be useful are:
$Sites = [Sitecore.Configuration.Factory]::GetSiteInfoList()
foreach($site in $Sites)
{
$language = $site.Language
$startItem = "$($site.RootPath)/$($site.StartItem)"
Write-Host "Language: " $language " Start Item: " $startItem
}
The above approach will not work for a Sitecore instance with SXA, as the Site Definitions go in the Site Groupings rather than the Site Configuration. Nevertheless, you can use the below snippet to get the sites for SXA.
I have used a ToArray call at the end of the script to make sure the output is always an array I can loop through. You can either remove that call or use the ToArray method from here.
$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 -and $_.TemplateId -eq [Constants]::SiteTemplateId} `
| Sort-Object -Unique | ToArray
This snippet can be used to get all the languages in the Sitecore instance.
Some of the situations where this can be useful are:
I have used a ToArray call at the end of the script to make sure the output is always an array I can loop through. You can either remove that call or use the ToArray method from here. Also, I use the master database to retrieve the languages. It can be changed as required.
$database = [Sitecore.Configuration.Factory]::GetDatabase("master")
$languages = $database.GetLanguages() | ToArray
Please let me know in the comments if you want me to add any Snippets. I will give it a try.
Happy Sitecoring!