我可以将一些文本发送到Windows下的活动进程的STDIN吗?

时间:2013-04-19 06:12:58

标签: windows powershell process batch-file console

我在网上搜索了这个问题并登陆了服务器故障:

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

似乎在Linux下实现这一目标非常容易。但我需要它来获得Win32命令提示符。

背景:我有一个轮询STDIN的应用程序,如果我按下 x 键,应用程序就会终止。现在,我想做一些自动化测试,测试应用程序然后关闭它。

注意:由于我正在调查关闭应用程序期间出现的问题,因此无法取消该进程。

1 个答案:

答案 0 :(得分:19)

.NET framework的ProcessProcessStartInfo类可用于创建和控制进程。由于Windows PowerShell可用于实例化.NET对象,因此可以从PowerShell中获得控制流程几乎每个方面的功能。

以下是如何将dir命令发送到cmd.exe进程(确保将其包装在.ps1文件中,然后执行脚本):

$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