How can I redirect standard I/O of a process created by another process

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Sahoo Sahoo 11 months ago.

  • Author
  • #31463
    Profile photo of Sahoo

    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 } }
    Start-Sleep -s 2 ;
    Start-Sleep -s 2 ;
    Start-Sleep -s 2 ;
    $cmdProcess.StandardInput.WriteLine("D:\batch_files\CC_Automation\test\") ;

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


    test stdio redirection of child process
    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation. All rights reserved.

  • #31934
    Profile photo of Don Jones
    Don Jones

    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.

  • #32188
    Profile photo of Sahoo

    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 "". I was wondering if same thing can be done in powershell.

You must be logged in to reply to this topic.