Some Useful Sitecore PowerShell Script Part 2
Hello Everyone, this is my continuation for Part1 where we have seem some powershell script which can be handy during our Sitecore development. In this part we will see some powershell script which can be useful to us.
Powershell script to find the all the link referrers of an item.
- Item path: Path of the item for which we need to find the where it is being getting used.
#Getting Item referrer
$props = @{
InfoTitle = "Referrers"
InfoDescription = "Lists all items that are using this item"
PageSize = 25
}
function Get-ItemReferrers {
$item = Get-Item -Path "{{Item path}}"
$linkDb = [Sitecore.Globals]::LinkDatabase
$links = $linkDb.GetReferrers($item)
foreach($link in $links){
$linkedItem = Get-Item -Path master:\ -ID $link.SourceItemID
$linkedItem
}
}
$items = Get-ItemReferrers
$items | Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Path"; Expression={$_.ItemPath} },
@{Label="Id"; Expression={$_.Id} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} }
Close-Window
Getting assigned Profile from Tracking field value of Page Items.
- Home Item : The item path where it should take the items.
$schilds = Get-ChildItem master:'{{Home Item}}' -Recurse -Language en-ca
foreach($ab in $schilds)
{
$tracker = New-Object Sitecore.Analytics.Data.TrackingField($ab.Fields["__tracking"]);
$profiles = $tracker.Profiles
$profileName = ""
foreach ($profile in $profiles)
{
$profileName = $profileName + '|'
foreach($v in $profile.Presets.Keys){
$profileName = $profileName + "$v"
}
}
write-host $ab.ID '$' $ab.Paths.FullPath '$' $profileName
}
Calling an Api from Powershell.
- {0} : API URL
- {1} : Query String Param 1
- {2} : Query String Param 2
- {3} : OAuth Token
Clear-Host
(Invoke-WebRequest '{0}?lang={1}¶m{2}' -Headers @{"X-CLIENT-AUTHORIZATION"="{3}"}).Content
Getting all renderings from Parent Rendering Item and store it in csv.
- {0} : Controller rendering Template ID
$items = @()
$sxaPath = "/sitecore/layout/Renderings/Feature"
$items += @(Get-ChildItem -Path $sxaPath -Recurse | Where-Object -Property TemplateId -eq -Value '{0}' | Select-Object @{Label="Group";Expression={$_.Parent.Name}}, @{Label="Path";Expression={$_.Paths.FullPath}}, DisplayName, Language, Id, Version, TemplateName)
$items | Export-Csv -Path "C:\temp\jj_renderings5.csv" -Delimiter ',' -NoTypeInformation
Update custom field(Tags) in Media document like PDF
# Function to find shared website corresponding tag id
function Get-MatchingItemValue {
param (
[string]$id
)
Write-Host "The parameter id: " $id
foreach ($item in $global:matchingItems) {
if ($item.Item2ID -eq $id) {
return $item.Item1ID
}
}
return $null
}
# Script with WhatIf support
$WhatIf = $true
# Define both source and destination tags folders
$folderPath1 = "{Shared Site tags}"
$folderPath2 = "{Current Site tags}"
# Define the path of the location where we need to update the tags
$locationPath = "{media library folder}"
# Define the language to consider
$language = "en"
$languages = @("en", "fr")
# Define the template name to filter by
$templateName = "Tag"
# Define the multilist field name
$treelistFieldName = "Tags"
$pagetemplateName = "Pdf"
# Get the items from the folders in the specified language and template
$folder1Items = Get-ChildItem -Path $folderPath1 -Recurse | Where-Object { $_.Language.Name -eq $language -and $_.TemplateName -eq $templateName }
$folder2Items = Get-ChildItem -Path $folderPath2 -Recurse | Where-Object { $_.Language.Name -eq $language -and $_.TemplateName -eq $templateName }
# Create a list to store the matching items
$global:matchingItems = @()
# Create a hash table to store the items from folder 1 for quick lookup
$folder1ItemsHashTable = @{}
foreach ($item in $folder1Items) {
$folder1ItemsHashTable[$item.Name] = $item
}
# Create a list to store the unmatching items
$unmatchingItems = @()
# Compare items based on their names, language, and template
foreach ($item2 in $folder2Items) {
if ($folder1ItemsHashTable.ContainsKey($item2.Name)) {
$item1 = $folder1ItemsHashTable[$item2.Name]
# Add matching items to the list
$global:matchingItems += @{
"Item1ID" = $item1.ID
"Item1Name" = $item1.Name
"Item1Path" = $item1.Paths.FullPath
"Item2ID" = $item2.ID
"Item2Name" = $item2.Name
"Item2Path" = $item2.Paths.FullPath
"Status" = "Matched"
}
}
else{
$unmatchingItems += @{
"Item2ID" = $item2.ID
"Item2Name" = $item2.Name
"Item2Path" = $item2.Paths.FullPath
"Status" = "UnMatched"
}
}
}
# Get the items from the specified location
foreach ($lg in $languages) {
$items = Get-ChildItem -Path $locationPath -Language $lg -Recurse | Where-Object { $_.TemplateName -eq $pagetemplateName}
# Iterate through the items
foreach ($item in $items) {
if ($item -ne $null) {
Write-Host "item path for validation: " $($item.Paths.FullPath)
# Get the treelist field value
$treelistValue = $item.Fields[$treelistFieldName].Value
# Check if the multilist field is not empty
if (![string]::IsNullOrEmpty($treelistValue)) {
Write-Host "The original treelistvalue before updating: " $treelistValue "- " $item.Language.Name
# Split the multilist field value into individual IDs
$ids = $treelistValue -split '\|'
# Iterate through the array and replace the value using for loop
for ($i = 0; $i -lt $ids.Length; $i++) {
$correspondingitemId = Get-MatchingItemValue -id $ids[$i]
Write-Host "Output from Function : " $correspondingitemId
if(![string]::IsNullOrEmpty($correspondingitemId)){
Write-Host "The tag id is not empty from shared site : " $correspondingitemId
$ids[$i] = $correspondingitemId
}
else
{
Write-Host "The corresponding tag id is empty: " $ids[$i]
}
}
$newTreelistValue = $ids -join '|'
Write-Host "The new treelistvalue after updating " $newTreelistValue "- " $item.Language.Name
if ($WhatIf) {
Write-Host "The new treelistvalue after updating - Dry Run: " $newTreelistValue "- " $item.Language.Name
Write-Host "Updated item - Dry Run: " $($item.Paths.FullPath)
}else{
# Begin editing the item
Write-Host "item path for updating: " $($item.Paths.FullPath)
$item.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$item.Fields[$treelistFieldName].Value = $newTreelistValue
# End editing the item
$item.Editing.EndEdit()
Write-Host "Updated item: " $($item.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$item.Editing.CancelEdit()
Write-Error "Failed to update item: $($item.Paths.FullPath)"
}
}
}
}
}
}
Creating variant item and adding to Headless main placeholder
# Function to find shared website corresponding tag id
function Update-Placeholder {
param (
[string]$path
[string]$lang
[string]$id
)
$AllowedControls = "Allowed Controls"
#Logic for updating allowed controls
$item = Get-Item -path $path -Language $lang
$treelistValue = ""
if($item -eq $null){
$item = Get-Item -path $path -Language "en"
}
if ($item.ID -eq "{9978B967-C22F-4D4F-966B-261DE8C0C802}") {
$treelistValue= $item.Fields["Renderings"].Value
if (![string]::IsNullOrEmpty($treelistValue)) {
$ids = $treelistValue -split '\|'
$newTreelistValue = ($ids -join '|') + '|' + $id
$item.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$item.Fields["Renderings"].Value = $newTreelistValue
# End editing the item
$item.Editing.EndEdit()
Write-Host "Updated item: " $($item.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$item.Editing.CancelEdit()
Write-Error "Failed to update item: $($item.Paths.FullPath)"
}
}else{
$item.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$item.Fields["Renderings"].Value = $id
# End editing the item
$item.Editing.EndEdit()
Write-Host "Updated item: " $($item.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$item.Editing.CancelEdit()
Write-Error "Failed to update item: $($item.Paths.FullPath)"
}
}
}
else {
$treelistValue = $item.Fields[$AllowedControls].Value
if (![string]::IsNullOrEmpty($treelistValue)) {
$ids = $treelistValue -split '\|'
$newTreelistValue = ($ids -join '|') + '|' + $id
$item.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$item.Fields[$AllowedControls].Value = $newTreelistValue
# End editing the item
$item.Editing.EndEdit()
Write-Host "Updated item: " $($item.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$item.Editing.CancelEdit()
Write-Error "Failed to update item: $($item.Paths.FullPath)"
}
}else{
$item.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$item.Fields[$AllowedControls].Value = $id
# End editing the item
$item.Editing.EndEdit()
Write-Host "Updated item: " $($item.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$item.Editing.CancelEdit()
Write-Error "Failed to update item: $($item.Paths.FullPath)"
}
}
}
}
function Create-Variant {
param (
[string]$path
[string]$lang
[string]$id
[string]$headlessVariantsTemplate
[string]$headlessvariantName
[string]$variantDefinitionTemplate
)
# Get the folder item in the specified language
$Headlessvariantitem = Get-Item -Path $path -Language $lang
$Compatiblerenderingfield = "Compatible renderings"
# Parameters
$variantNames = @("Outline", "Primary", "Secondary") # Names of the variants to create
if ($Headlessvariantitem -ne $null) {
Write-Host "Folder found: $($Headlessvariantitem.Paths.FullPath)"
$newVariantParentItem = New-Item -Name $HeadlessvariantName -ItemType $headlessVariantsTemplate -Parent $Headlessvariantitem -Language $lang
$compatibleRenderingfieldvalue = $newVariantParentItem.Fields[$Compatiblerenderingfield].Value
if (![string]::IsNullOrEmpty($compatibleRenderingfieldvalue)) {
$cids = $compatibleRenderingfieldvalue -split '\|'
$newValue = ($cids -join '|') + '|' + $id
$newVariantParentItem.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$newVariantParentItem.Fields[$Compatiblerenderingfield].Value = $newValue
# End editing the item
$newVariantParentItem.Editing.EndEdit()
Write-Host "Updated item: " $($newVariantParentItem.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$newVariantParentItem.Editing.CancelEdit()
Write-Error "Failed to update item: $($newVariantParentItem.Paths.FullPath)"
}
}else{
$newVariantParentItem.Editing.BeginEdit()
try {
# Set the new value for the multilist field
$newVariantParentItem.Fields[$Compatiblerenderingfield].Value = $id
# End editing the item
$newVariantParentItem.Editing.EndEdit()
Write-Host "Updated item: " $($newVariantParentItem.Paths.FullPath)
}
catch{
# Cancel the edit if something goes wrong
$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 $lang
if ($newVariant -ne $null) {
Write-Host "Rendering Variant '$variantName' created successfully under '$($newVariantParentItem.Paths.FullPath)' in language '$lang'."
} else {
Write-Error "Failed to create Rendering Variant '$variantName'."
}
}
}
}
# Create some objects
$objects = @(
(New-Object PSObject -Property @{
language = "en"
headlessmainplaceholderpath = "{Headless Main Placeholder Path}"
Headlessvariantpath = "{Headless Variant Path}"
}),
(New-Object PSObject -Property @{
language = "pt-br"
headlessmainplaceholderpath = "{Headless Main Placeholder Path}"
Headlessvariantpath = "{Headless Variant Path}"
})
)
#Adding component to allowed control in headless main placeholder
$ComponentID = "{04B18958-BBFE-413A-B47A-267A623FBCCC}"
$HeadlessVariantsTemplate = "{49C111D0-6867-4798-A724-1F103166E6E9}"
$VariantDefinitionTemplate = "{4D50CDAE-C2D9-4DE8-B080-8F992BFB1B55}"
$HeadlessvariantName = "CtaButton"
$VariantsRequired = $true
# Loop through each object and add it to the array
for ($i = 0; $i -lt $objects.Count; $i++) {
Write-Host "The value of langauge - " $objects[$i].language " Value Placeholder Path " $objects[$i].headlessmainplaceholderpath " Value Variant Path " $objects[$i].Headlessvariantpath
Update-Placeholder -path $objects[$i].headlessmainplaceholderpath -lang $objects[$i].language -id $ComponentID
if($VariantsRequired){
Create-Variant -path $objects[$i].Headlessvariantpath -lang $objects[$i].language -id $ComponentID -headlessVariantsTemplate $HeadlessVariantsTemplate -headlessvariantName $HeadlessvariantName -variantDefinitionTemplate $VariantDefinitionTemplate
}
}
Thanks for reading. Hope this will be helpful. See you in next blog
Happy Learning. Happy Sitecoring!!
Comments
Post a Comment