Author Posts

October 29, 2015 at 2:18 am

I have started a process using System.Diagnostics.Process::start() with redirected stdi/o. This process creates another process. I want to redirect the stdi/o of the second process in powershell.

Here is a sample code in which i am running a perl script from cmd.exe process created using System.Diagnostics.Process::start(). I want to see the output of the perl script in the log file as well as send key strokes to the perl interpreter.

Powershell script:

$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") ;

hello.pl:

print "Hello\n";
print "press Enter key to exit";
$key = ;

Output:Log.txt

test stdio redirection of child process
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\System32\WindowsPowerShell\v1.0>D:\batch_files\CC_Automation\test\hello.pl

November 13, 2015 at 11:34 am

So you're launching Process A, but it in turn is launching Process B? Then it would be up to Process A to capture or redirect the output of Process B. There's no way for PowerShell to sub-capture if Process A isn't doing it.

November 22, 2015 at 9:16 pm

Yeah, Process B is launching its "conhost.exe" which is i guess the console process to display the output. However there is something like this in "C" in "https://support.microsoft.com/en-us/kb/190351". I was wondering if same thing can be done in powershell.