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.
1
# Create a list of field names on the Standard Template. This will help us filter out extraneous fields.
2
$standardTemplate = Get-Item -Path "master:" -ID "{1930BBEB-7805-471A-A3BE-4858AC7CF696}"
3
$standardTemplateTemplateItem = [Sitecore.Data.Items.TemplateItem]$standardTemplate
4
$standardFields = $standardTemplateTemplateItem.OwnFields + $standardTemplateTemplateItem.Fields | Select-Object -ExpandProperty key -Unique
5
6
$itemTemplate = Get-Item -Path "master:" -ID "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}"
7
$itemTemplateTemplateItem = [Sitecore.Data.Items.TemplateItem]$itemTemplate
8
$itemTemplateFields = $itemTemplateTemplateItem.OwnFields + $itemTemplateTemplateItem.Fields | Select-Object -ExpandProperty key -Unique
9
10
$filterFields = $itemTemplateFields | Where-Object { $standardFields -notcontains $_ } | Sort-Object
Copied!

Parse Html

Example: The following demonstrates the use of the HtmlAgilityPack for parsing html.
1
$html = "<ul><li>foo</li><li>bar</li></ul>"
2
$htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
3
$htmlDocument.LoadHtml($html)
4
foreach($x in $htmlDocument.DocumentNode.SelectNodes("//li")) {
5
$x.InnerText;
6
}
Copied!
Example: The following demonstrates how to update text in the document and exclude certain nodes.
1
$html = @"
2
<div class="kitchen">
3
<div class="kitchen">
4
<blockquote>kitchen<br />
5
<span class="kitchen">kitchen</span>
6
</blockquote>
7
<a><img title="kitchen" src="https://kitchen-sink.local" /></a>
8
</div>
9
</div>
10
"@
11
12
$htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
13
$htmlDocument.LoadHtml($html)
14
foreach($x in $htmlDocument.DocumentNode.Descendants()) {
15
if($x.Name -ne "img" -and ![string]::IsNullOrEmpty($x.Text)) {
16
$x.Text = $x.Text.Replace("kitchen", "sink")
17
}
18
}
19
20
$htmlDocument.DocumentNode.OuterHtml
Copied!
Example: The following demonstrates how to remove empty paragraph tags in an html field.

Workflow History

Example: The following prints the workflow history of the home item.
1
$item = Get-Item -Path "master:" -Id "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"
2
3
$db = Get-Database -Name "master"
4
$workflowProvider = $db.WorkflowProvider
5
6
foreach($version in $item.Versions.GetVersions()) {
7
$workflowEvents = $workflowProvider.HistoryStore.GetHistory($version)
8
foreach($workflowEvent in $workflowEvents) {
9
"[$($workflowEvent.Date)] ($($workflowEvent.User)) $(($workflowEvent.Text -replace '(\r|\n)',''))"
10
}
11
}
Copied!

Restore Recycle bin items

Example: The following restores items in the media library that were removed yesterday. Credit @technomaz.
1
Write-Host "Restoring items recycled after $($archivedDate.ToShortDateString())"
2
3
foreach($archive in Get-Archive -Name "recyclebin") {
4
Write-Host " - Found $($archive.GetEntryCount()) entries"
5
$entries = $archive.GetEntries(0, $archive.GetEntryCount())
6
foreach($entry in $entries) {
7
if($entry.ArchiveLocalDate -ge $archivedDate) {
8
Write-Host "Restoring item: $($entry.OriginalLocation) {$($entry.ArchivalId)}on date $($entry.ArchiveLocalDate)"
9
$archive.RestoreItem($entry.ArchivalId)
10
} else {
11
Write-Host "Skipping $($entry.OriginalLocation) on date $($entry.ArchiveLocalDate)"
12
}
13
}
14
}
Copied!

Run JavaScript

Example: The following logs messages to the browser console and then alerts the user with a message.
1
1..5 | ForEach-Object {
2
Start-Sleep -Seconds 1
3
Invoke-JavaScript -Script "console.log('Hello World! Call #$($_) from PowerShell...');"
4
}
5
6
Invoke-JavaScript -Script "alert('hello from powershell');"
Copied!
Invoke JavaScript

Remoting

1
Import-Module -Name SPE -Force
2
3
$packageName = "$($SitecorePackageFolder)\[PACKAGE].zip"
4
5
$session = New-ScriptSession -Username "admin" -Password "b" -ConnectionUri "https://remotesitecore"
6
Test-RemoteConnection -Session $session -Quiet
7
$jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
8
[Sitecore.Configuration.Settings+Indexing]::Enabled = $false
9
Get-SearchIndex | ForEach-Object { Stop-SearchIndex -Name $_.Name }
10
Import-Package -Path "$($SitecorePackageFolder)\$($using:packageName)" -InstallMode Merge -MergeMode Merge
11
[Sitecore.Configuration.Settings+Indexing]::Enabled = $true
12
} -AsJob
13
Wait-RemoteScriptSession -Session $session -Id $jobId -Delay 5 -Verbose
14
Stop-ScriptSession -Session $session
Copied!
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.
Last modified 1yr ago