我可以在 Windows 下向活动进程的 STDIN 发送一些文本吗? [英] Can I send some text to the STDIN of an active process under Windows?
问题描述
我在网上搜索了这个问题,结果是服务器故障:
I searched the web for that question and landed on Server Fault:
我可以向在 screen 会话中运行的活动进程的 STDIN 发送一些文本吗?
在 Linux 下实现这一点似乎非常容易.但我需要它用于 Win32 命令提示符.
Seems like it is ridiculously easy to achieve this under Linux. But I need it for a Win32 Command Prompt.
背景:我有一个轮询 STDIN 的应用程序,如果我按下 x 键,应用程序将终止.现在,我想做一些自动化测试,测试应用程序,然后将其关闭.
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.
推荐答案
.NET 框架的 Process 和 ProcessStartInfo 类可用于创建和控制过程.由于 Windows PowerShell 可用于实例化 .NET 对象,因此可以从 PowerShell 中控制进程的几乎所有方面.
.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.
以下是将 dir
命令发送到 cmd.exe
进程的方法(确保将其包装在 .ps1 文件中,然后执行脚本):
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
这篇关于我可以在 Windows 下向活动进程的 STDIN 发送一些文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!