Automating an executable on command line that only takes interactive arguments (can't specify arguments at execution time)

Viewed 1847

I have an executable that I can run interactively from the commandline. Here is how it looks:

C:\Users\Me> my_executable.exe  # Running the executable from CMD

Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2             # I entered this interactively

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2
Enter your input: 1             # I entered this interactively

I cannot specify the input arguments before-hand using flags. For instance, nothing of this sort works:

C:\Users\Me> my_executable.exe 2 # Running the executable from CMD with first argument specified

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2

Enter your input: 

What would be the right way to automate this using a batch file? I came across a similar requirement in this SO thread, but the difference is that the executable there takes command-line arguments (unlike in my case).

2 Answers

Assuming your executable reads stdin, and does not access the keyboard directly, then you can use redirection or a pipe to provide all of the responses needed to complete the run.

Let's assume that you want the 2, 1 responses you indicated, but then after the server connection is achieved the exe loops back to the first menu. Assuming you want to quit, you would also need to follow up with 0.

To use redirection, you need to prepare a text file with all of the needed responses, one response per line.

@echo off
> response.txt (
  echo 2
  echo 1
  echo 0
)
my_executable.exe < response.txt
del response.txt

Or you might prefer to use a FOR loop

@echo off
(for %%A in (2 1 0) do echo %%A) > response.txt
my_executable.exe < response.txt
del response.txt

You can avoid the temporary file if you use a pipe

@echo off
(
  echo 2
  echo 1
  echo 0
) | my_executable

or with a FOR loop

@echo off
(for %%A in (2 1 0) do echo %%A) | my_executable

I had similar problem automating installation of golden gate monitoring agent instance in windows server, following sample helped -

[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}")
Related