How can I make and run a PowerShell script prompt for input?
When it comes to running a PowerShell script prompt for input, admins can get the best results by letting PowerShell do most of the work. Here's how.
How can I run a PowerShell script prompt for input and get the best results?
Continue Reading This Article
Enjoy this article as well as all of our content, including E-Guides, news, tips and more.
There are a variety of ways to do this, but the best way is to let PowerShell do most of the work. Consider this script:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,HelpMessage="Enter one or more computer names")]
[string[]]$ComputerName
)
ForEach ($computer in $computername) {
# $computer has one name - do something with it
}
This script defines the –ComputerName parameter (shown as $ComputerName in the Param() block) as mandatory, meaning PowerShell will prompt for values if they're not provided. A help message is also provided, although the Console host doesn't display it by default. Run the script with no parameters and you'll get this:
PS C:\> .\test.ps1
Cmdlet test.ps1 at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
ComputerName[0]: !?
Enter one or more computer names
ComputerName[0]: localhost
ComputerName[1]: server2
ComputerName[2]:
I've shown my input in boldface. By typing !?, you can display the HelpMessage for the parameter. Because this parameter was coded as [string[]] and not [string], it will accept multiple values. Just hit Enter on an empty prompt to tell the shell you're done entering values, and you're ready to execute the script.
About the author
Don Jones is a well-known and respected PowerShell expert and educator. He's co-author of three books on PowerShell (see PowerShellBooks.com for a list). You can find his content online, including his PowerShell Q&A forums, by visiting DonJones.com.