Home » Sitecore PowerShell Extensions
Category Archives: Sitecore PowerShell Extensions
Expand Tokens on Items Using a Sitecore PowerShell Extensions Toolbox Script
Last Wednesday I had the opportunity of presenting Sitecore PowerShell Extensions (SPE) at the Milwaukee Sitecore Meetup. During this presentation, I demonstrated how quickly and easily one can add, execute and reuse PowerShell scripts in SPE, and I did this using version 3.0 of SPE on Sitecore XP 8.
During one segment of the presentation, I shared how one can seamlessly add scripts to the SPE Toolbox — a repository of utility scripts if you will — and used the following script when showing this:
<# .NAME Expand tokens in all content items .SYNOPSIS Expand tokens in all fields in all content items .NOTES Mike Reynolds #> $items = Get-ChildItem -Path "master:\sitecore\content" -Recurse $items | ForEach-Object { $_.Fields.ReadAll() } $items | Expand-Token Close-Window
The script above grabs all descendant Items under /sitecore/content/; iterates over them to ensure all field values are available — the ReadAll() method on the FieldCollection instance will ensure values from fields on the Item’s template’s Standard Values Item are pulled in for processing; and sends in these Items into the Expand-Token commandlet which comes “out of the box” with SPE.
The script also closes the processing dialog.
I then saved the above script into my Toolbox library in my SPE module:
Let’s try this out. Let’s find some Items with tokens in some fields. It looks like the Home Item has some:
Here’s another Item that also has tokens:
Let’s go to the SPE Toolbox, and click on our Toolbox utility:
As you can see the tokens were expanded on the Home Item:
Tokens were also expanded on the descendant Item:
If you have any thoughts and/or suggestions on this, or have ideas for other SPE Toolbox scripts, please drop a comment.
If you would like to watch the Milwaukee Sitecore Meetup presentation where I showed the above — you’ll also get to see some epic Sitecore PowerShell Extensions stuff from Adam Brauer, Senior Product Engineer at Active Commerce, in this presentation as well — have a look below:
If you would like to see another example of adding a script to the SPE Toolbox, please see my previous post on this subject.
Until next time, have a scriptaculous day!
Bucket Items in Sitecore using a Custom Commandlet in Sitecore PowerShell Extensions
Last Wednesday I had the privilege to present Sitecore PowerShell Extensions (SPE) at the Milwaukee Sitecore Meetup. During my presentation, I demonstrated how easy it is to add, execute and reuse PowerShell scripts in SPE, and I showcased version 3.0 of SPE on Sitecore XP 8.
Unfortunately, I ran out of time before showing how one can go about creating a custom commandlet in SPE, and hope to make it up to everyone by sharing the commandlet I wrote for the presentation in this post.
I wrote the following commandlet to convert an Item into an Item Bucket in Sitecore:
using System; using System.Management.Automation; using Sitecore.Data.Items; using Sitecore.Shell.Framework.Commands; using Cognifide.PowerShell.Commandlets; using Cognifide.PowerShell.Commandlets.Interactive.Messages; namespace Sitecore.Sandbox.SPE.Commandlets.Buckets { [Cmdlet(VerbsData.ConvertTo, "Bucket"), OutputType(new Type[] { typeof(Item) })] public class ConvertToBucketCommand : BaseItemCommand { protected override void ProcessItem(Item item) { try { PutMessage(new ShellCommandInItemContextMessage(item, "item:bucket")); } catch (Exception exception) { WriteError(new ErrorRecord(exception, "sitecore_new_bucket_error", ErrorCategory.NotSpecified, Item)); } WriteItem(Item); } } }
The above commandlet implements the ProcessItem() method — this method is declared abstract in one of the ancestor classes of the class above — and leverages the framework of SPE to invoke a Sheer UI command to bucket the Item passed to the method — one of the ancestor classes of this class passes the Item to be processed.
The above highlights how in SPE we are employing the Template method pattern for many “out of the box” commandlets. This involves inheriting from an abstract base class — Cognifide.PowerShell.Commandlets.BaseItemCommand in Cognifide.PowerShell.dll (this assembly comes with the SPE module) is an example of one of these base classes — and implementing methods that are defined as abstract. The parent or an ancestor class will do the brunt of the work behind the scenes, and use your method implementation for specifics.
As a side note, we also provide method hooks as well — these are virtual methods defined on a base or ancestor class — which you can override to change how they work to meet your particular needs.
I then wired the above up using a Sitecore include configuration file:
<?xml version="1.0" encoding="utf-8" ?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <powershell> <commandlets> <add Name="Custom Bucket Commandlets" type="*, Sitecore.Sandbox.SPE" /> </commandlets> </powershell> </sitecore> </configuration>
I deployed the above to my Sitecore instance; loaded up the Integrated Scripting Environment (ISE) in SPE; and saw that my commandlet was registered using the Control-Space shortcut key:
Let’s take this for a spin. Let’s convert the Home Item into an Item Bucket:
Here’s my script to do that:
I clicked the execute button, and then got this confirmation dialog:
I then clicked the “Ok” button and was immediately presented with this dialog:
As you can see it worked! The Home Item in my content tree is now an Item Bucket:
If you have any thoughts on this or ideas for other custom commandlets for SPE, please share in a comment.
If you would like to watch the Milwaukee Sitecore Meetup presentation where I showcased Sitecore PowerShell Extensions — and as a bonus you’ll also get to see some real-life application of SPE from Adam Brauer, Senior Product Engineer at Active Commerce, in this presentation as well — it has been recorded for posterity, and you can watch it here:
Until next time, stay curious, keep experimenting, and let’s keep on sharing all the Sitecore things!
Add Scripts to the PowerShell Toolbox in Sitecore PowerShell Extensions
During our ‘Take charge of your Sitecore instance using Sitecore tools’ session at Sitecore Symposium 2014 Las Vegas, Sitecore MVP Sean Holmesby and I shared how easy it is to leverage/extend popular Sitecore development tools out there, and built up a fictitious Sitecore website where we pulled in #SitecoreSelfie Tweets.
The code that pulls in these Tweets is supposed to follow a naming convention where Tweet IDs are appended to Media Library Item names, as you can see here:
Sadly, right before our talk, I mistakenly 😉 made a code change which broke our naming convention for some images:
Upon further investigation, we had discovered our issue was much larger than anticipated: all Selfie Media Library Item names do not end with their Tweet IDs:
To fix this, I decided to create a PowerShell Toolbox script in Sitecore PowerShell Extensions using the following script:
<# .SYNOPSIS Rename selfie image items to include tweet ID where missing. .NOTES Mike Reynolds #> $items = Get-ChildItem -Path "master:\sitecore\content\Social-Media\Twitter\Tweets" -Recurse | Where-Object { $_.TemplateName -eq "Tweet" } $changedItems = @() foreach($item in $items) { $tweetID = $item["TweetID"] $selfieImageField = [Sitecore.Data.Fields.ImageField]$item.Fields["SelfieImage"] $selfieImage = $selfieImageField.MediaItem if($selfieImage -ne $null -and -not $selfieImage.Name.EndsWith($tweetID)) { $oldName = $selfieImage.Name $newName = $oldName + "_" + $tweetID $selfieImage.Editing.BeginEdit() $selfieImage.Name = $newName $selfieImage.Editing.EndEdit() $changedItem = New-Object PSObject -Property @{ Icon = $selfieImage.Appearance.Icon OldName = $oldName NewName = $newName Path = $selfieImage.Paths.Path Alt = $selfieImage["Alt"] Title = $selfieImage["Title"] Width = $selfieImage["Width"] Height = $selfieImage["Height"] MimeType = $selfieImage["Mime Type"] Size = $selfieImage["Size"] } $changedItems += $changedItem } } if($changedItems.Count -gt 0) { $changedItems | Show-ListView -Property @{Label="Icon"; Expression={$_.Icon} }, @{Label="Old Name"; Expression={$_.OldName} }, @{Label="New Name"; Expression={$_.NewName} }, @{Label="Path"; Expression={$_.Path} }, @{Label="Alt"; Expression={$_.Alt} }, @{Label="Title"; Expression={$_.Title} }, @{Label="Width"; Expression={$_.Width} }, @{Label="Height"; Expression={$_.Height} }, @{Label="Mime Type"; Expression={$_.MimeType} }, @{Label="Size"; Expression={$_.Size} } } else { Show-Alert "There are no selfie image items missing tweet IDs in their name." } Close-Window
The above PowerShell script grabs all Tweet Items in Sitecore; ascertains whether referenced Selfie images in the Media Library — these are referenced in the “SelfieImage” field on the Tweet Items — end with the Tweet IDs of their referring Tweet Items (the Tweet ID is stored in a field on the Tweet Item); and renames the Selfie images to include their Tweet IDs if not. The script also launches a dialog showing the images that have changed.
To save the above script in the PowerShell Toolbox, I launched the PowerShell Integrated Scripting Environment (ISE) in Sitecore PowerShell Extensions:
I pasted in the above script, and saved it in the PowerShell Toolbox library:
As you can see, our new script is in the PowerShell Toolbox:
I then clicked the new PowerShell Toolbox option, and was presented with the following dialog:
The above dialog gives information about the images along with their old and new Item names.
I then navigated to where these images live in the Media Library, and see that they were all renamed to include Tweet IDs:
If you have any thoughts on this, or suggestions for other PowerShell Toolbox scripts, please share in a comment.
Until next time, have a #SitecoreSelfie type of day!
Make Bulk Item Updates using Sitecore PowerShell Extensions
In my Sitecore PowerShell Extensions presentation at the Sitecore User Group Conference 2014, I demonstrated how simple it is to make bulk Item updates — perform the same update to multiple Sitecore items — using a simple PowerShell script, and thought I would write down what I had shown.
Sadly, I do not remember which script I had shared with the audience — the scratchpad text file I referenced during my presentation contains multiple scripts for making bulk updates to Items (if you attended my talk, and remember exactly what I had shown, please drop a comment).
Since I cannot recall which script I had shown — please forgive me 😉 — let’s look at the following PowerShell script (this might be the script I had shown):
@(Get-Item .) + (Get-ChildItem -r .) | ForEach-Object { Expand-Token $_ }
This script grabs the context Item — this is denoted by a period — within the PowerShell ISE via the Get-Item command, and puts it into an array so that we can concatenate it with an array of all of its descendants — this is returned by the Get-ChildItem command with the -r parameter (r stands for recursive). The script then iterates over all Items in the resulting array, passes each to the Expand-Token command — this command is offered “out of the box” in Sitecore PowerShell Extensions — which expands tokens in every field on the Item.
Let’s see this in action!
My home Item has some tokens in its Title field:
One of its descendants also has tokens in its Title field:
I opened up the PowerShell ISE, wrote my script, and executed:
As you can see, the tokens on the home Item were expanded:
They were also expanded on the home Item’s descendant:
If you have any thoughts or questions on this, please share in a comment.
Execute PowerShell Scripts in Scheduled Tasks using Sitecore PowerShell Extensions
At the Sitecore User Group Conference 2014, I demonstrated how to invoke PowerShell scripts in a Sitecore Scheduled Task using Sitecore PowerShell Extensions, and felt I should pen what I had shown in a blog post — yes, you guessed it: this is that blog post. 😉
In my presentation, I shared the following PowerShell script with the audience:
ForEach($site in [Sitecore.Configuration.Factory]::GetSiteNames()) { $siteInfo = [Sitecore.Configuration.Factory]::GetSiteInfo($site) if($siteInfo -ne $null) { $siteInfo.HtmlCache.Clear() $logEntry = [string]::Format("HtmlCache.Clear() invoked for {0}", $siteInfo.Name) Write-Log $logEntry } }
The script above iterates over all sites in your Sitecore instance, clears the Html Cache for each, and creates log entries expressing the Html Cache was cleared for all sites processed.
You would probably never have to use a script like the one above. I only wrote it for demonstration purposes since I couldn’t think of a more practical example to show. If you can think of any practical examples, or feel the script above has some practicality, please share in a comment.
I wrote, tested, and saved the above script in the PowerShell ISE:
The PowerShell script was saved to a new Item created by the dialog above:
I then created a Schedule Item to invoke the script housed in the Item above (to learn more about Sitecore Scheduled Tasks, please see John West‘s post discussing them):
I saved my Item, waited a bit, and opened up my latest Sitecore log file:
As you can see, the Html Cache was cleared for each site in my Sitecore instance.
If you have any questions/comments/thoughts on this, please drop a comment.