Sitecore PowerShell Extensions has a very powerful dialog feature that allows scripts to be written that create dialogs for capturing information from the user.

This feature is used by a great deal of the scripts that come bundled with SPE, such as the broken links report:

And the package generator:

If you have a script featuring a dialog that you regularly execute, you might want to have your most recently used values saved, so that next time you execute the script you can skip through the dialog. Fortunately, this is actually quite easy to accomplish.

Using the User Profile

There are a number of different locations you could use to persist this data. Assuming you wish to save the values on a per-user basis, one of the easiest methods is to use the ASP.NET User Profile. This is part of the ASP.NET Membership Provider that Sitecore’s user management is built upon. Using the profile means that the data will be stored within SQL Server and therefore persisted across multiple browser sessions and machines. Furthermore, the Sitecore API and SPE makes accessing this profile very simple.

Getting the current user and setting / getting a profile value from it couldn’t be simpler:

1
2
3
4
5
6
7
8
# Get the current user
$user = Get-User -Current
# Store a value
$user.Profile.SetCustomProperty("mycustomproperty", "store this please!")
# Read a value
$user.Profile.GetCustomProperty("mycustomproperty")

Straightforward, right?

A sample script

Let’s use the above example and apply it to a script that uses a dialog. In this example, we will show a simple dialog with a dropdown list. When the dialog is completed, the value that was selected will be stored in the current user’s profile, ready for next time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
$profileKey = "myScript_savedOption"
$me = Get-User -Current
# Read the last saved value from the user profile, if any.
# This will get set in the dialog as the default value.
$savedValue = $me.Profile.GetCustomProperty($profileKey)
$options = [ordered]@{
"Option One"="1"
"Option Two"="2"
"Option Three"="3"
}
$props = @{
Parameters = @(
@{Name="chosenOption"; Title="Choose an option"; Options=$options; Value=$savedValue}
)
Title = "Persistant option selector"
Description = "Choose an option, your choice will be saved for next time."
Width = 300
Height = 300
ShowHints = $true
}
$result = Read-Variable @props
# Only proceed if the user selected OK in the dialog.
if($result -ne "ok")
{
return
}
# Save the value in the user profile for next time
$me.Profile.SetCustomProperty($profileKey, $chosenOption)
# Can now proceed to use $chosenOption in the script

If you execute the script, you will see that once you have completed the dialog once, the value you last selected is preselected for you the next time you run the script. Easy, right?