1

I open a cmd script using

$a = start-process cmd.exe -argumentlist "/c M:\loc\to\file.cmd" -passthru
start-sleep -seconds 5
#Send ENTER KEY

Sometimes the cmd window will take longer than 5 seconds to load from the network, and my ENTER keystroke does not take because the cmd window has not displayed the "press any key to continue" point in the process.

Is there a way I can get my script to wait for the $a process to display that "press any key to continue" text inside the cmd window before sending my ENTER keystroke?

RC-IT
  • 11
  • 1
  • `Start-Process` doesn't have that functionality, but you can redirect the standard output stream and read it using `System.Diagnostics.Process` instead. [Here](https://stackoverflow.com/a/8762068/10601203) is an answer explaining how to do that. – Jesse Aug 25 '22 at 17:06

1 Answers1

0

Rather than trying to send keystrokes, which isn't reliable, it's better to provide responses via stdin (standard input).

If a pause statement is the only statement in your batch file that reads from stdin, you can provide pass an empty file to Start-Process' -RedirectStandardInput parameter - pause will then automatically continue:

# Create an empty temporary file.
$tmpEmptyFile = New-TemporaryFile

# Note: Batch files can be launched directly - no need for "cmd /c"
$a = Start-process M:\loc\to\file.cmd -PassThru -RedirectStandardInput $tmpEmpty File 

# ... 
# Don't forget to delete $tmpEmptyFile once the process has terminated.

Note:

  • Note that this technique wouldn't work if you wanted to keep the cmd.exe session that runs the batch file open (with cmd /k), because the redirected (empty) stdin input also prevents entering an interactive session.

  • The solution would be easier if you ran the batch file directly and synchronously in the current console window, in which case you can simply use the pipeline operator, |, and pipe the empty string:

    '' | M:\loc\to\file.cmd
    
mklement0
  • 382,024
  • 64
  • 607
  • 775