Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

XML
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
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900