AtE

How can I make and run a PowerShell script prompt for input?

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: