22

I searched the web for that question and landed on Server Fault:

Can I send some text to the STDIN of an active process running in a screen session?

Seems like it is ridiculously easy to achieve this under Linux. But I need it for a Win32 Command Prompt.

Background: I have an application that polls STDIN and if I press the x key, the application terminates. Now, I want to do some automated testing, test the application and then shut it down.

Note: Just killing the process is not an option since I'm currently investigating problems that arise during the shutdown of my application.

Community
  • 1
  • 1
eckes
  • 64,417
  • 29
  • 168
  • 201
  • This might be difficult to do in batch file but if you are using Windows Powershell, you can instantiate a Process object, call it's 'Start' method to run your application and then give text input to the process's 'StandardInput' property. – Abbas Apr 19 '13 at 06:34
  • @Abbas: If you could elaborate a bit more on this (i.e. code sample), you would earn rep... – eckes Apr 19 '13 at 07:37

1 Answers1

26

.NET framework's Process and ProcessStartInfo classes can be used to create and control a process. Since Windows PowerShell can be used to instantiate .NET objects, the ability to control almost every aspect of a process is available from within PowerShell.

Here's how you can send the dir command to a cmd.exe process (make sure to wrap this in a .ps1 file and then execute the script):

$psi = New-Object System.Diagnostics.ProcessStartInfo;
$psi.FileName = "cmd.exe"; #process file
$psi.UseShellExecute = $false; #start the process from it's own executable file
$psi.RedirectStandardInput = $true; #enable the process to read from standard input

$p = [System.Diagnostics.Process]::Start($psi);

Start-Sleep -s 2 #wait 2 seconds so that the process can be up and running

$p.StandardInput.WriteLine("dir"); #StandardInput property of the Process is a .NET StreamWriter object
Abbas
  • 6,720
  • 4
  • 35
  • 49
  • Getting exception: Exception calling "Start" with "1" argument(s): "Access is denied" At C:\git\a.ps1:9 char:1 + $p = [System.Diagnostics.Process]::Start($psi); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : Win32Exception – Piepypye Jul 26 '21 at 19:26
  • @Piepypye It sounds like you're trying to run a program or cmdlet that requires Administrator privileges. Try adding `$psi.Verb = "runas"` before starting the process. This will ask your OS for elevated permissions through UAC in Windows. – Mavaddat Javid Jan 19 '22 at 19:44