简体   繁体   中英

How to request user input from the command line (at the same time that you run the script from the command line)

I have a PowerShell script named Script.ps1. This script has a Read-Host input prompt but I want to make the input BEFORE running the script.

For example:

C:\User\Desktop\Script.ps1 -input hello

This is the part of the script that requests the input:

$D = Read-Host -Prompt "Input here"

You can create a script file that prompts the user when parameter binding happens or at the command line.

Prompting User At Command Line:

Script.ps1 Contents:

param(
    [string]$in
)
"the input was $in"

Running the Script:

C:\User\Desktop\Script.ps1 -in (Read-Host "Input Here")

Output:

input here: Hello
the input was Hello

Prompting User During Parameter Binding:

Script.ps1 Contents:

param(
    [string]$in = (Read-Host "Input Here")
)
"the input was $in"

Executing Script:

C:\User\Desktop\Script.ps1

Output:

Input Here: hello
the input was hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM