Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

powershell - 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:

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...