Useful PowerShell scripts for a Sitecore developer

#1. Insert a user in Sitecore using the Sitecore PowerShell Extensions (SPE):
# Set the user credentials
$userName = "user1"
$password = "passw0rd123"
$email = "user1@example.com"
$role = "sitecore\ContentAuthor"  # Specify the desired role
# Get the user manager
$userManager = Get-UserManager
# Check if the user already exists
if ($userManager.GetUser($userName) -eq $null) {
    # Create a new user
    $newUser = $userManager.CreateUser($userName, $password, $email, $null)
    # Add the user to the specified role
    if ($newUser -ne $null) {
        $roleProvider = [Sitecore.SecurityModel.Roles.RoleManager]::GetRoleProvider("switcher")
        # Get the role
        $sitecoreRole = $roleProvider.GetRole($role)
        # Add the user to the role
        $sitecoreRole.AddMember($newUser)
        
        Write-Host "User '$userName' created and added to the '$role' role."
    } else {
        Write-Host "Failed to create the user."
    }
} else {
    Write-Host "User '$userName' already exists."
}
#2. Create self-signed certificate for dev environment:
- Open a PowerShell console and execute the following command.
- Replace “www.demo.dev.local” by your own site URL and “web-sc-dev” by a name of your choice.
New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName "www.demo.dev.local" -FriendlyName "web-sc-dev" -NotAfter (Get-Date).AddYears(5)
- This will create a self-signed certificate for your site that is valid for 5 years.
- Now you should copy this certificate to the Trusted Root Certification Authorities store.
#3. Script to enable item level Language fallback:
$sourcePath = "master:/sitecore/content/Home/Site1"
$items = Get-ChildItem -Path $sourcePath -Recurse
$rootItem = Get-Item -Path $sourcePath
$items = $items + $rootItem
foreach($item in $items){
    if ($item.Fields["__Enable Item Fallback"].Value -ne "1")
    {
        $item.Editing.BeginEdit();
        $item.Fields["__Enable Item Fallback"].Value = '1'
        $item.Editing.EndEdit();
        Write-Host $item.ID $item.Fields["__Enable Item Fallback"].Value $item.Paths.Path
    }
 
}
#4. Update Workflow state for an Item:
# Set the item path
$itemPath = "/sitecore/content/Home/YourItemPath"
# Set the target workflow state
$targetWorkflowState = "Approved"
# Get the item
$item = Get-Item -Path $itemPath
if ($item -ne $null) {
    # Set the workflow state for the item
    $item.Editing.BeginEdit()
    $item.Fields["__Workflow state"].Value = $targetWorkflowState
    $item.Editing.EndEdit()
    Write-Host "Workflow state updated to '$targetWorkflowState' for item '$itemPath'."
} else {
    Write-Host "Item not found at path '$itemPath'."
}
#5. Add / Remove Workflow:
# Set the item path
$itemPath = "/sitecore/content/Home/YourItemPath"
# Get the item
$item = Get-Item -Path $itemPath
# Set workflow ID to assign a Workfolw to the item
$workflowID = "{7CFB68EE-5E9A-4D36-9E4C-A47D667B87FB}"
if ($item -ne $null) {
   
    $item.Editing.BeginEdit()
    
    # Remove the workflow from the item
    $item.Fields["__Workflow"].Reset()
    
    # Assign the workflow to the item
     $item.Fields["__Workflow"] = $workflowID
    
    $item.Editing.EndEdit()
    Write-Host "Workflow added/removed from item '$itemPath'."
} else {
    Write-Host "Item not found at path '$itemPath'."
}
#6. Remove the renderings of items:
$sourcePath = "master:/sitecore/content/Home/Site1"
$items = Get-ChildItem -Path $sourcePath -Recurse
foreach($item in $items)
{
    if ($item.TemplateId -eq "{BAAF9E6D-000F-4C58-9BDF-E0E6F04EF5A9}")
    {
        $item.Editing.BeginEdit();
        $item.Fields["__Renderings"].Value = ""
        $item.Fields["__Final Renderings"] = ""
        $item.Editing.EndEdit();
        Write-Host "Renderings removed for: " $item.ID " 
    }
}
#7. Unlock all locked items:
 $sourcePath = "/sitecore/content/Site1/Home"
 $items = Get-ChildItem -Path $sourcePath -Recurse
 $rootItem = Get-Item -Path $sourcePath
 $items = $items + $rootItem
 foreach ($item in $items)
 {
  foreach ($version in $item.Versions.GetVersions($true))
  {
      if($version.Locking.IsLocked())
      {
        $version.Editing.BeginEdit();
        $version.Locking.Unlock();
        $version.Editing.EndEdit();
        Write-Host "Item un-locked:" $item.ID $version.Language;
      }
   }
 }
#8. Get item publishing date and path
$path = "master:/sitecore/content/My Content/Articles"
$templateName = "Article Page Template"
$items = Get-ChildItem –Path $path –Recurse | Where-Object { $_.TemplateName -eq $templateName }
foreach($item in $items) {
    
  $dateTime = ([sitecore.dateutil]::IsoDateToDateTime($item["Publish Date"]))
  Write-Host ($item.ItemPath + "| Publish Date: " + $dateTime.ToString("dd MMMM yyyy"))
}
#9. Get updated item details in last 5 days
$path ="master:/sitecore/content/Global Content/Articles"
$items = Get-ChildItem -Path $path -Recurse | Where-Object { $_.__Updated -gt [datetime]::Now.AddDays(-5) }
ForEach ($item in $items)
{
    Write-Host $item.ID $item.Paths.Path $item."__Updated By"
}
Write-Host "Total item updated : " $items.Count
#10. Publish an item:
# Set the item path
$itemPath = "/sitecore/content/Home/YourItemPath"
# Get the item
$item = Get-Item -Path $itemPath
if ($item -ne $null) {
    # Publish the item
    $publishOptions = New-Object Sitecore.Publishing.PublishOptions($item.Database, [System.DateTime]::Now, "full", [Sitecore.SecurityModel.Authentication.AuthenticationManager]::GetActiveUser())
    $publisher = New-Object Sitecore.Publishing.Publisher($publishOptions)
    $publisher.Options.RootItem = $item
    $publisher.Publish()
    
    Write-Host "Item '$itemPath' published successfully."
} else {
    Write-Host "Item not found at path '$itemPath'."
}
I trust that this blog will provide you with helpful and practical scripts. I also commit to consistently updating this blog with useful scripts in the future.
Thanks!
Comments
Post a Comment