Q

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?

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

Dig deeper on Windows PowerShell Scripting

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchServerVirtualization

SearchCloudComputing

SearchExchange

SearchSQLServer

SearchWinIT

SearchEnterpriseDesktop

SearchVirtualDesktop

Close