asgallant
asgallant

Reputation: 26340

How to make a Powershell script answer a prompt for user input?

I have a Powershell script that needs to execute a command-line executable that prompts for user input (for which there is no command-line parameter). Something like this:

# promptsForInput.ps1
$someInput = Read-Host "Gimme some input"
# do something with $someInput

The actual executable is a compiled binary which I cannot modify, but this example script do for the purposes of this question. My Powershell script calls the executable:

# myScript.ps1
.\promptsForInput.ps1

At runtime, I get prompted to input something:

> .\myScript.ps1
Gimme some input:

I need to be able to fill in that input request without user intervention. When promptsForInput.ps1 prompts for user input, I need myScript.ps1 to enter the required value and proceed with script execution.

Similar questions on SO either have answers specific to the particular exe, or are otherwise unhelpful:

Upvotes: 16

Views: 41897

Answers (2)

Vijred
Vijred

Reputation: 379

Following sample I used to run batch file and provide inputs

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Start-Process -FilePath C:\myexecbatchfile.bat

# Wait the application start for 2 sec 
Start-Sleep -m 2000
 
# Send keys
[System.Windows.Forms.SendKeys]::SendWait("input1")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Start-Sleep -m 3000

[System.Windows.Forms.SendKeys]::SendWait("input2")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

Upvotes: 4

Bill_Stewart
Bill_Stewart

Reputation: 24585

  1. Don't use $input as the name of a variable as that's an automatic variable in PowerShell (see help about_Automatic_Variables).

  2. Determine whether the executable can accept command-line arguments instead of stopping or prompting for input. This is obviously preferred if it is available.

  3. Whether you can tell PowerShell to automatically send input to an arbitrary executable depends upon the design of that executable. If the executable allows you to send standard input to it, you can run something like

    "test" | myexecutable.exe
    

    In this example, PowerShell will provide the string test and a return as standard input to the executable. If the executable accepts standard input, then this will work.

    If the executable does not use standard input, then you will have to do something different like send keystrokes to the window. I consider sending keystrokes a last resort and a brittle solution that is not automation-friendly.

Upvotes: 8

Related Questions