Sitecore PowerShell Extensions
  • Introduction
  • Disclaimer
  • Installation
    • Contributor Guide
  • Training
  • Community
  • Interfaces
    • Console
    • Scripting
    • Interface Configuration
    • Interactive Dialogs
    • Help
  • Working with Items
    • Item Languages
    • Item Renderings
    • Variables
    • Providers
  • Modules
    • Libraries and Scripts
    • Integration Points
      • Content Editor
      • Control Panel
      • Data Sources
      • Event Handlers
      • Functions
      • ISE Plugins
      • Page Editor
      • Pipelines
      • Reports
        • Authoring Reports
      • Tasks
        • Authoring Tasks
      • Toolbox
      • Web API
      • Workflows
    • Packaging
  • Remoting
  • Security
    • Users and Roles
  • Releases
  • Troubleshooting
  • Code Snippets
    • Item Links
    • Field Types
    • Manage Templates
  • Appendix
    • Common
      • Add-BaseTemplate
      • Add-ItemVersion
      • Close-Window
      • ConvertFrom-CliXml
      • ConvertFrom-ItemClone
      • ConvertTo-CliXml
      • Expand-Token
      • Get-Archive
      • Get-ArchiveItem
      • Get-Cache
      • Get-Database
      • Get-ItemClone
      • Get-ItemCloneNotification
      • Get-ItemField
      • Get-ItemReference
      • Get-ItemReferrer
      • Get-ItemTemplate
      • Get-ItemWorkflowEvent
      • Get-SitecoreJob
      • Get-SpeModule
      • Get-SpeModuleFeatureRoot
      • Get-TaskSchedule
      • Get-UserAgent
      • Import-Function
      • Invoke-JavaScript
      • Invoke-Script
      • Invoke-ShellCommand
      • Invoke-Workflow
      • New-ItemClone
      • New-ItemWorkflowEvent
      • New-UsingBlock
      • Out-Download
      • Publish-Item
      • Read-Variable
      • Receive-File
      • Receive-ItemCloneNotification
      • Remove-BaseTemplate
      • Remove-ArchiveItem
      • Remove-ItemVersion
      • Reset-ItemField
      • Restart-Application
      • Restore-ArchiveItem
      • Send-File
      • Send-SheerMessage
      • Set-HostProperty
      • Set-ItemTemplate
      • Show-Alert
      • Show-Application
      • Show-Confirm
      • Show-FieldEditor
      • Show-Input
      • Show-ListView
      • Show-ModalDialog
      • Show-Result
      • Show-YesNoCancel
      • Start-TaskSchedule
      • Test-BaseTemplate
      • Test-Rule
      • Update-ItemReferrer
      • Update-ListView
      • Write-Log
    • Indexing
      • Find-Item
      • Get-SearchIndex
      • Initialize-Item
      • Initialize-SearchIndex
      • Initialize-SearchIndexItem
      • Remove-SearchIndexItem
      • Resume-SearchIndex
      • Stop-SearchIndex
      • Suspend-SearchIndex
    • Packaging
      • Export-Item
      • Export-Package
      • Export-UpdatePackage
      • Get-Package
      • Get-Preset
      • Get-UpdatePackageDiff
      • Import-Item
      • Install-Package
      • Install-UpdatePackage
      • New-ExplicitFileSource
      • New-ExplicitItemSource
      • New-FileSource
      • New-ItemSource
      • New-SecuritySource
      • Import-Item
      • New-Package
    • Presentation
      • Add-PlaceholderSetting
      • Add-Rendering
      • Get-Layout
      • Get-LayoutDevice
      • Get-PlaceholderSetting
      • Get-Rendering
      • Get-RenderingParameter
      • Merge-Layout
      • New-PlaceholderSetting
      • New-Rendering
      • Remove-PlaceholderSetting
      • Remove-Rendering
      • Remove-RenderingParameter
      • Reset-Layout
      • Set-Layout
      • Set-Rendering
      • Set-RenderingParameter
      • Switch-Rendering
    • Provider
      • Get-Item
    • Security
      • Add-ItemAcl
      • Add-RoleMember
      • Clear-ItemAcl
      • Disable-User
      • Enable-User
      • Export-Role
      • Export-User
      • Get-Domain
      • Get-ItemAcl
      • Get-Role
      • Get-RoleMember
      • Get-User
      • Import-Role
      • Import-User
      • Lock-Item
      • Login-User
      • Logout-User
      • New-Domain
      • New-ItemAcl
      • New-Role
      • New-User
      • Protect-Item
      • Remove-Domain
      • Remove-Role
      • Remove-RoleMember
      • Remove-User
      • Set-ItemAcl
      • Set-User
      • Set-UserPassword
      • Test-Account
      • Test-ItemAcl
      • Unlock-Item
      • Unprotect-Item
      • Unlock-User
    • Session
      • Get-ScriptSession
      • Get-Session
      • Receive-ScriptSession
      • Remove-ScriptSession
      • Remove-Session
      • Start-ScriptSession
      • Stop-ScriptSession
      • Wait-ScriptSession
Powered by GitBook
On this page
  • List fields on template
  • Media item url
  • Parse Html
  • Workflow History
  • Restore Recycle bin items
  • Purge Recycle bin items
  • Run JavaScript
  • Remoting
Export as PDF

Code Snippets

Useful code snippets to help you with those complex scripts.

List fields on template

Example: The following demonstrates how to list all of the fields of a template excluding the Standard Template fields.

# Create a list of field names on the Standard Template. This will help us filter out extraneous fields.
$standardTemplate = Get-Item -Path "master:" -ID "{1930BBEB-7805-471A-A3BE-4858AC7CF696}"
$standardTemplateTemplateItem = [Sitecore.Data.Items.TemplateItem]$standardTemplate
$standardFields = $standardTemplateTemplateItem.OwnFields + $standardTemplateTemplateItem.Fields | Select-Object -ExpandProperty key -Unique

$itemTemplate = Get-Item -Path "master:" -ID "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}"
$itemTemplateTemplateItem = [Sitecore.Data.Items.TemplateItem]$itemTemplate
$itemTemplateFields = $itemTemplateTemplateItem.OwnFields + $itemTemplateTemplateItem.Fields | Select-Object -ExpandProperty key -Unique

$filterFields = $itemTemplateFields | Where-Object { $standardFields -notcontains $_ } | Sort-Object

Media item url

Example: The following demonstrates how to generate the public facing url from a media item.

$item = Get-Item -Path "master:{04DAD0FD-DB66-4070-881F-17264CA257E1}"
$siteName = "website"

$site = [Sitecore.Sites.SiteContextFactory]::GetSiteContext($siteName)
New-UsingBlock (New-Object Sitecore.Sites.SiteContextSwitcher $site) {
    [Sitecore.Resources.Media.MediaManager]::GetMediaUrl($item)
}

# /-/media/default-website/cover.jpg

Parse Html

Example: The following demonstrates the use of the HtmlAgilityPack for parsing html.

$html = "<ul><li>foo</li><li>bar</li></ul>"
$htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
$htmlDocument.LoadHtml($html)
foreach($x in $htmlDocument.DocumentNode.SelectNodes("//li")) {
    $x.InnerText;
}

Example: The following demonstrates how to update text in the document and exclude certain nodes.

$html = @"
<div class="kitchen">
   <div class="kitchen">
        <blockquote>kitchen<br />
            <span class="kitchen">kitchen</span>
        </blockquote>
        <a><img title="kitchen" src="https://kitchen-sink.local" /></a>
    </div>
</div>
"@

$htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
$htmlDocument.LoadHtml($html)
foreach($x in $htmlDocument.DocumentNode.Descendants()) {
    if($x.Name -ne "img" -and ![string]::IsNullOrEmpty($x.Text)) {
        $x.Text = $x.Text.Replace("kitchen", "sink")
    }
}

$htmlDocument.DocumentNode.OuterHtml

Example: The following demonstrates how to remove empty paragraph tags in an html field.

Example: The following demonstrates removing style attributes from the html.

$html = @"
<div style='padding: 10px 10px;'>Some Text</div>
"@

$htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
$htmlDocument.LoadHtml($html)
$nodes = $htmlDocument.DocumentNode.SelectNodes("//@style");
foreach($node in $nodes) {
    $node.Attributes["style"].Remove()
}
$htmlDocument.DocumentNode.OuterHtml

Workflow History

Example: The following prints the workflow history of the home item.

$item = Get-Item -Path "master:" -Id "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"

$db = Get-Database -Name "master"
$workflowProvider = $db.WorkflowProvider

foreach($version in $item.Versions.GetVersions()) {
    $workflowEvents = $workflowProvider.HistoryStore.GetHistory($version)
    foreach($workflowEvent in $workflowEvents) {
        "[$($workflowEvent.Date)] ($($workflowEvent.User)) $(($workflowEvent.Text -replace '(\r|\n)',''))"
    }
}

Restore Recycle bin items

Write-Host "Restoring items recycled after $($archivedDate.ToShortDateString())"

foreach($archive in Get-Archive -Name "recyclebin") {
    Write-Host " - Found $($archive.GetEntryCount()) entries"
    $entries = $archive.GetEntries(0, $archive.GetEntryCount())
    foreach($entry in $entries) {
        if($entry.ArchiveLocalDate -ge $archivedDate) { 
            Write-Host "Restoring item: $($entry.OriginalLocation) {$($entry.ArchivalId)}on date $($entry.ArchiveLocalDate)"
            $archive.RestoreItem($entry.ArchivalId)
        } else {
            Write-Host "Skipping $($entry.OriginalLocation) on date $($entry.ArchiveLocalDate)"
        }
    }
}

Purge Recycle bin items

Example: The following will incrementally purge items from the recycle bin (master db) with a progress counter.

$database = Get-Database -Name "master"
$archiveName = "recyclebin"
$archive = Get-Archive -Database $database -Name $archiveName
$items = Get-ArchiveItem -Archive $archive

$count = 0
$total = $items.Count
foreach($item in $items) {
    $count++
    if($count % 100 -eq 0) {
        Write-Host "[$(Get-Date -Format 'yyyy-MM-dd hh:mm:ss')] $([math]::round($count * 100 / $total, 2))% complete"
    }
    $item | Remove-ArchiveItem
}
Write-Host "Completed processing recycle bin"

Run JavaScript

Example: The following logs messages to the browser console and then alerts the user with a message.

1..5 | ForEach-Object { 
    Start-Sleep -Seconds 1
    Invoke-JavaScript -Script "console.log('Hello World! Call #$($_) from PowerShell...');" 
}

Invoke-JavaScript -Script "alert('hello from powershell');"

Remoting

Import-Module -Name SPE -Force

$packageName = "$($SitecorePackageFolder)\[PACKAGE].zip"

$session = New-ScriptSession -Username "admin" -Password "b" -ConnectionUri "https://remotesitecore"
Test-RemoteConnection -Session $session -Quiet
$jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
    [Sitecore.Configuration.Settings+Indexing]::Enabled = $false
    Get-SearchIndex | ForEach-Object { Stop-SearchIndex -Name $_.Name }
    Import-Package -Path "$($SitecorePackageFolder)\$($using:packageName)" -InstallMode Merge -MergeMode Merge
    [Sitecore.Configuration.Settings+Indexing]::Enabled = $true
} -AsJob
Wait-RemoteScriptSession -Session $session -Id $jobId -Delay 5 -Verbose
Stop-ScriptSession -Session $session
PreviousTroubleshootingNextItem Links

Last updated 2 years ago

Example: The following restores items in the media library that were removed yesterday. @technomaz.

Example:

Not seeing what you are looking for? You can always check out some Github Gists that and have shared or the .

Sitecore Stack Exchanage
Credit
Remote Package Installation
Adam
Michael
Sitecore Stack Exchange
Invoke JavaScript