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