2013-04-13 40 views
1

我使用System.Diagnostics.Process,因为它允许我得到错误代码和相关的错误。只重定向stderr,保持标准输出指向控制台使用System.Diagnostics.Process

但是,当我设置StartInfo.RedirectStandardOutput = $false输出没有回显到我的控制台窗口,所以目前我被迫添加额外的by-ref参数$ stdout并从调用函数中回显它。

这是不理想的,因为一些命令可能会产生大量的文本,我担心缓冲区溢出。

任何方式,我仍然可以使用类似的System.Diagnostics.Process代码,仍然捕获错误字符串,但让输出流动到控制台正常,无需重定向到标准输出?

function Run([string] $runCommand,[string] $runArguments,[ref] [string] $stderr) 
{ 
    $p = New-Object System.Diagnostics.Process 
    $p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo; 
    $p.StartInfo.FileName = $runCommand 
    $p.StartInfo.Arguments = $runArguments 
    $p.StartInfo.CreateNoWindow = $true 
    $p.StartInfo.RedirectStandardError = $true 
    $p.StartInfo.RedirectStandardOutput = $false 
    $p.StartInfo.UseShellExecute = $false 

    $p.Start() | Out-Null 
    $p.WaitForExit() 

    $code = $p.ExitCode 
    $stderr.value = $p.StandardError.ReadToEnd() 

    # what I have been doing is using a stdout by-ref variable and echoing out contents 
    # $stdout.value = $p.StandardOutput.ReadToEnd() 

    return $code 
} 

回答

2

您可能不需要使用System.Diagnostics.Process对象。只需执行EXE并获取如下信息:

$stdout = .\foo.exe 2> fooerr.txt 
Get-Content fooerr.txt 
return $LastExitCode 
相关问题