Code Snippets

Last updated last month

Useful code snippets to help you with those complex scripts.

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
foreach($x in $htmlDocument.DocumentNode.SelectNodes("//li")) {

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

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

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)"
} else {
Write-Host "Skipping $($entry.OriginalLocation) on date $($entry.ArchiveLocalDate)"

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');"
Invoke JavaScript

Example: Remote Package Installation

Import-Module -Name SPE -Force
$packageName = "$($SitecorePackageFolder)\[PACKAGE].zip"
$session = New-ScriptSession -Username "admin" -Password "b" -ConnectionUri "http://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

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