我已经使用 System.Diagnostics.Process::start() 和重定向的 stdi/o 启动了一个进程。这个过程创建了另一个过程。我想在powershell中重定向第二个进程的stdi/o。
这是一个示例代码,我在其中运行使用 System.Diagnostics.Process::start() 创建的 cmd.exe 进程的 perl 脚本。我想在日志文件中查看 perl 脚本的输出,并将击键发送到 perl 解释器。
Powershell脚本:
$LogFilePath = ((get-location).ToString() + "\Log.txt");
"test stdio redirection of child process" > $LogFilePath;
$cmdProcess = New-Object System.Diagnostics.Process;
$cmdProcess.StartInfo.FileName = "cmd.exe"
$cmdProcess.StartInfo.UseShellExecute = $false;
$cmdProcess.StartInfo.RedirectStandardInput = $true;
$cmdProcess.StartInfo.RedirectStandardOutput = $true;
$cmdProcess.StartInfo.RedirectStandardError = $true;
Register-ObjectEvent $cmdProcess ErrorDataReceived -SourceIdentifier "cmdProcess.ErrorDataReceived" -Action { if(![string]::IsNullOrEmpty($EventArgs.Data)) { $EventArgs.Data | Add-Content $global:LogFilePath } }
Register-ObjectEvent $cmdProcess OutputDataReceived -SourceIdentifier "cmdProcess.OutputDataReceived" -Action { if(![string]::IsNullOrEmpty($EventArgs.Data)) { $EventArgs.Data | Add-Content $global:LogFilePath } }
$cmdProcess.start()
Start-Sleep -s 2 ;
$cmdProcess.BeginErrorReadLine();
Start-Sleep -s 2 ;
$cmdProcess.BeginOutputReadLine();
Start-Sleep -s 2 ;
$cmdProcess.StandardInput.WriteLine("D:\batch_files\CC_Automation\test\hello.pl") ;
你好.pl:
print "Hello\n";
print "press Enter key to exit";
$key = <>;
输出:Log.txt
测试子进程的 stdio 重定向 Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。版权所有。C:\Windows\System32\WindowsPowerShell\v1.0>D:\batch_files\CC_Automation\test\hello.pl
我在“C”中发现了类似的东西:https: //support.microsoft.com/en-us/kb/190351