
Implementing User Input with Read-Variable in SPE


May 22, 2019
The Sitecore PowerShell Extensions (SPE) module speeds up the delivery of Sitecore solutions by helping you automate tasks with interactive tools for your custom scripts.
In this post, I’ll share a very useful SPE command, Read-Variable, which is a powerful, yet simple way of adding user input to SPE scripts.
Basics
The Read-Variable function in SPE allows a user to input the necessary parameters in a customizable dialog box to run your script. (Check out the full Read-Variable documentation here.)
You can create one or more PowerShell hash tables to specify each of the parameters that you pass to the Read-Variable function:
$dialogParams = @{
Title = "Dialog title"
Description = "Description under title"
OkButtonName = "Execute"
CancelButtonName = "Close"
Parameters = @(
@{
Name = "textField"
Title = "Text Field"
}
)
}
$dialogResult = Read-Variable @dialogParams
If you run this code snippet in the PowerShell ISE, you will get the following dialog:
To determine if the user has pressed the "Ok" button ("Execute" in the example) or the "Cancel" button ("Close" in the example), just test the dialog result variable ($dialogResult in the example) to see if it equal to "ok":
if ($dialogResult -ne "ok") {
Exit
}
To read the user input (which is the purpose of this mechanism), take note of each of the Parameters' "Name" value. For the example, we have a single Parameter named "textField". We refer to the entered value by using it like any other PowerShell variable. In this example we use $textField:
Write-Host "Value entered by user: " $textField
The return type of the Parameter will depend on the editor that you used for it. In this example, the editor is a simple text box, so you will get a string for $textField. If you use other editors like a droplist, you can get a Sitecore Item object, or an array of Items if using multi-list editors. We will talk about Parameter Editors in my next post.
Finally, you should always close the Script window after your script has finished running. Make sure to end your scripts with the following sentence:
Close-Window
This will ensure that the "Running script" dialog that appears when running a custom script from the Sitecore interface (outside of the PowerShell ISE) will automatically close.
Part 1: Implementing User Input with Read-Variable in SPE
Part 2: How to define fields in the dialog box using Parameters in Read-Variable
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.