Category Archives: Powershell

Cleaning Up Unused Data Sources in Sitecore with PowerShell

As Sitecore developers and content managers, we often encounter situations where unused data sources clutter our content tree. This can happen after restructuring or deleting items, leaving behind orphaned data sources that are no longer in use. To keep our Sitecore instance clean and efficient, it’s essential to identify and remove these unused data sources. In this post, I’ll walk you through a PowerShell script designed to find and remove unused data sources within a specific content path.

The Challenge

When working with Sitecore, especially in large content trees, managing data sources can become cumbersome. Unused data sources not only waste storage space but can also lead to confusion when searching for relevant items. The goal of the script is to traverse a specified path, check each item for referrers, and remove those without any references.

The PowerShell Script

Here’s a cleaned-up and more professional version of the PowerShell script that accomplishes this task:

# Navigate to the specified path in the master database
cd 'master:/sitecore/content/[Your-Site-Path]'

# Get all items under the specified path, recursively
$itemsToProcess = Get-ChildItem -Recurse

if ($itemsToProcess -ne $null) {
    # Process each item to check for referrers
    $itemsToProcess | ForEach-Object {
        $referrers = Get-ItemReferrer -Item $_ | Measure-Object

        if ($referrers.Count -gt 0) {
            Write-Host "Item ID: $($_.ID), Referrers: YES, Name: $($_.Name)"
        } else {
            Write-Host "Item ID: $($_.ID), Referrers: NO, Name: $($_.Name)"
            # Uncomment the following line to remove unused items
            # $_ | Remove-Item -Force
        }
    }
} else {
    Write-Host "No items found to process."
}

How the Script Works

  1. Navigating to the Path: The script begins by navigating to the specified content path in the master database where the data sources are located.
  2. Retrieving Items: It retrieves all items under the specified path recursively.
  3. Checking for Referrers: For each item, the script checks if there are any referrers using the Get-ItemReferrer command. This command returns the items that reference the current item.
  4. Outputting Results:
    • If the item has referrers, it outputs the item’s ID, name, and states that it has referrers.
    • If the item does not have any referrers, it indicates that the item can be considered for removal.
  5. Removal (Optional): The line responsible for removing the item is commented out by default for safety. You can uncomment it when you are ready to perform the deletion.

Conclusion

This PowerShell script provides a straightforward way to clean up unused data sources in Sitecore, helping maintain an organized content structure. Remember to review the items carefully before removal, especially in production environments.

Before running the removal command, consider taking a backup of your Sitecore instance or using a staging environment to ensure that no important data is lost.

Final Note

Always test scripts in a safe environment before executing them in production, and customize the path and parameters as necessary for your specific use case. Happy scripting!

Automating Workflow State Changes in Sitecore Using PowerShell

While working on a Sitecore SXA project, I needed to create a new site by cloning an existing one and performing various updates. As part of this process, I ended up with a large number of items in a draft state, which needed to be transitioned to the final workflow state. Manually publishing each item was not feasible due to the sheer volume, so I created a PowerShell script to automate this task by updating the workflow state of all items to the final state.

In this post, I’ll walk you through the problem, the solution, and provide a cleaned-up version of the PowerShell script I used to accomplish this.

The Problem

In Sitecore, when creating or cloning a site, content items often remain in the draft state or some intermediate workflow state. If you have a lot of items, moving them to the final state manually via the Sitecore interface is tedious and time-consuming.

The solution? Use Sitecore PowerShell Extensions (SPE) to script the process, which allows you to:

  • Automate the transition of items to the final workflow state.
  • Handle multiple languages and content tree hierarchies.
  • Output a summary of the total items checked and updated.

The Solution: PowerShell Script to Update Workflow States

Here’s the cleaned-up version of the PowerShell script I used to change the workflow state for all items under a specific site path to the final state. This script runs in the context of Sitecore’s SPE module.

PowerShell Script for Updating Items to Final Workflow State

# Begin a bulk update context to optimize the process
New-UsingBlock (New-Object Sitecore.Data.BulkUpdateContext) {

    # Define the root path of the site you want to update
    $rootItemPath = "master:/sitecore/content/YourSite/YourSiteName"
    
    # Define the languages you want to support
    $languages = @("en")  # Add more languages as needed

    # The final workflow state GUID (replace with your own)
    $workflowFinalState = "{Your-Final-Workfow-State-ID}"

    $updatedItemsCount = 0
    $checkedItemsCount = 0

    # Hashtable to track updated items by language
    $updatedItemsPerLanguage = @{}

    # Loop through each language
    foreach ($language in $languages) {

        # Initialize count for this language
        $updatedItemsPerLanguage[$language] = 0

        # Get the root item in the current language
        $rootItem = Get-Item -Path $rootItemPath -Language $language

        # Retrieve the root item and its children
        $items = @($rootItem) + (Get-ChildItem -Item $rootItem -Recurse -Language $language)

        foreach ($item in $items) {
            if ($item -ne $null) {
                $checkedItemsCount++
                
                # Get the current workflow state
                $currentWorkflowState = $item["__Workflow state"]

                # If the item's workflow state is not already in the final state, update it
                if ($currentWorkflowState -ne $workflowFinalState) {
                    $item.Editing.BeginEdit()
                    $item.Fields["__Workflow state"].Value = $workflowFinalState
                    $item.Editing.EndEdit() > $null
                    Write-Host "$($item.Paths.FullPath) in $language --> Updated"
                    $updatedItemsCount++
                    $updatedItemsPerLanguage[$language]++
                } else {
                    Write-Host "$($item.Paths.FullPath) in $language --> Already in the desired state"
                }
            }
        }
    }

    # Output summary of the process
    Write-Host "Total items checked: $checkedItemsCount"
    Write-Host "Total items updated: $updatedItemsCount"

    # Display the number of updated items per language
    foreach ($lang in $languages) {
        Write-Host "Items updated in $lang: $($updatedItemsPerLanguage[$lang])"
    }
}

How the Script Works:

  1. Bulk Update Context: The script begins with New-UsingBlock (New-Object Sitecore.Data.BulkUpdateContext) to ensure the updates are processed efficiently and without performance bottlenecks. This is crucial when updating many items.
  2. Language Support: The $languages array allows you to define the languages in which the items exist. In this example, it’s set to "en" for English, but you can add other language codes like "fr", "de", etc.
  3. Final Workflow State: The $workflowFinalState variable holds the GUID of the final workflow state. You’ll need to replace this with the correct GUID for the final state in your workflow.
  4. Recursive Item Fetching: The script retrieves the root item and its children using Get-ChildItem with the -Recurse flag. This ensures all items under the root path are included.
  5. Workflow State Check: For each item, the script checks if it’s already in the final workflow state. If not, it updates the __Workflow state field and commits the change.
  6. Summary: After processing, the script outputs a summary showing how many items were checked and updated, broken down by language.

How to Run the Script

  1. Install Sitecore PowerShell Extensions (SPE): If you don’t already have SPE installed on your Sitecore instance, you’ll need to install it. This module allows you to execute PowerShell scripts inside Sitecore.
  2. Run the Script: Open the PowerShell ISE or PowerShell Console in Sitecore under the Control Panel and paste the script. Adjust the $rootItemPath, $languages, and $workflowFinalState as necessary for your environment.
  3. Execute: Run the script. The output will show the paths of the items being updated and provide a summary at the end.

When Should You Use This?

This script is handy when:

  • You’ve cloned a site and need to batch update all items to their final workflow state.
  • Items remain stuck in draft or intermediate workflow states after deployment.
  • You’re working with multilingual sites and need to ensure content across different languages is published.
  • You want to automate workflow transitions for large sets of content.

Conclusion

Automating workflow state transitions in Sitecore using PowerShell not only saves time but also ensures consistency across large batches of content items. By using this script, you can efficiently update thousands of items, taking care of language-specific versions and ensuring everything is in the correct final workflow state.