
close
close
Chance to win $250 in Petri 2023 Audience Survey
When you are building a PowerShell script, there might be situations where you want to prompt for a piece of data. Some cmdlets like Get-Credential do that sort of task implicitly. You can also get prompting if you define a mandatory parameter in a function or script. Otherwise, we tend to rely on PowerShell’s Read-Host cmdlet. With this cmdlet, you provide a prompt message and PowerShell writes the object back to the pipeline.
$r = Read-Host "Enter computername"
Using Read-Host (Image Credit: Jeff Hicks)
Simulating Read-Host (Image Credit: Jeff Hicks)
$r = $host.ui.Prompt("SERVER REPORTING","Enter a computername","Name")
A simple UI prompt (Image Credit: Jeff Hicks)
Viewing prompt result (Image Credit: Jeff Hicks)
Using the collections object (Image Credit: Jeff Hicks)
$r = $host.ui.Prompt("SERVER REPORTING","Enter values for these settings:",@("Computername","Domain","Operating System","Version"))
Prompting for multiple values (Image Credit: Jeff Hicks)
$s = New-Object -TypeName PSObject -Property $r
Creating an object from the collection (Image Credit: Jeff Hicks)
Testing properties (Image Credit: Jeff Hicks)
Function Read-MyHost { [cmdletbinding()] Param( [Parameter(Position=0,Mandatory,HelpMessage="Enter the message prompt.")] [ValidateNotNullorEmpty()] [string]$Message, [Parameter(Position=1,Mandatory,HelpMessage="Enter key property name or names separated by commas.")] [System.Management.Automation.Host.FieldDescription []]$Key, [Parameter(HelpMessage = "Text to display as a title for the prompt.")] [string]$PromptTitle = "", [Parameter(HelpMessage = "Convert the result to an object.")] [switch]$AsObject ) $response = $host.ui.Prompt($PromptTitle,$Message,$Key) if ($AsObject) { #create a custom object New-Object -TypeName PSObject -Property $response } else { #write the result to the pipeline $response } } #end function
The title, while required for Prompt method, can be an empty string, so I didn’t make it a mandatory parameter. You probably also noticed the type name for the Key parameter. The Prompt() method is looking for parameters of this type so I’ll have PowerShell force them to be so. I also added a switch to write the result as an object to the pipeline to save a step.
Here’s a simple test:
A simple test of the new function (Image Credit: Jeff Hicks)
Prompting for multiple entries (Image Credit: Jeff Hicks)
Modifying the object (Image Credit: Jeff Hicks)
More in PowerShell
Most popular on petri