T.Richter
T.Richter

Reputation: 63

How to send input to console application from PowerShell

After starting an adb shell console application with a powershell script, I would like to automate the user inpute to this console application.

adb shell "/usr/bin/console_app"

Is there a way to have the powershell script enter those console inputs as well an don't have it wait for the user inputs?

Something like:

adb shell "/usr/bin/console_app"
sleep -s 5 <# wait for app to start#>
1 <# user input for menu selection#>

Thanks!

Upvotes: 1

Views: 1936

Answers (1)

marsze
marsze

Reputation: 17055

My preferred solution:

$startInfo = New-Object 'System.Diagnostics.ProcessStartInfo' -Property @{
    FileName = "adb"
    Arguments = "shell", "/usr/bin/console_app"
    UseShellExecute = $false
    RedirectStandardInput = $true
}
$process = [System.Diagnostics.Process]::Start($startInfo)
Start-Sleep -Seconds 5
$process.StandardInput.WriteLine("1")

You could also try to wait for the application to finish starting by reading the output:

# set this on the ProcessStartInfo:
RedirectStandardOutput = $true

# wait while application returns stdout
while ($process.StandardOutput.ReadLine()) { }

The following will also work with non-console applications, but might not work well within non-interactive contexts:

Add-Type -AssemblyName 'System.Windows.Forms', 'Microsoft.VisualBasic'
$id = (Start-Process "adb" -ArgumentList "shell", "/usr/bin/console_app" -PassThru).Id
Start-Sleep -Seconds 5
[Microsoft.VisualBasic.Interaction]::AppActivate($id)
[System.Windows.Forms.SendKeys]::SendWait("1~")

Upvotes: 2

Related Questions