How can I run a PowerShell script prompt for input and get the best results?
Requires Free Membership to View
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.
This was first published in February 2013
Enterprise Server Strategies for the CIO
Join the conversationComment
Share
Comments
Results
Contribute to the conversation