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.

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

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

Sitecore Stack Exchanagearrow-up-right

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

Workflow History

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

Restore Recycle bin items

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

Purge Recycle bin items

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

Run JavaScript

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

Invoke JavaScript

Remoting

Example: Remote Package Installationarrow-up-right

Not seeing what you are looking for? You can always check out some Github Gists that Adamarrow-up-right and Michaelarrow-up-right have shared or the Sitecore Stack Exchangearrow-up-right.

Last updated