2010-07-07 55 views
2
后台作业

我知道PowerShell有与Start-JobWait-Job等后台作业的功能,但它是可以使用Process类从System.Diagnostics在.NET中实现同样的事情?如果是这样,那么执行此操作的最佳方法是什么?它会对运行后台作业的默认Powershell机制有什么优势?使用systemdiagnostics.process运行在PowerShell中

回答

2

你当然可以使用Process对象为“开始”的可执行文件异步地与你回来,你可以测试一下,看看是否EXE已完成或终止该进程的进程对象。诀窍是获取输出和错误流信息,而不会在程序运行时干扰控制台,因此您可以执行其他操作。从MSDN文档,它看起来像使用BeginOutputReadLine可能做的伎俩:

// Start the child process. 
Process p = new Process(); 
// Redirect the output stream of the child process. 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.FileName = "Write500Lines.exe"; 
p.Start(); 
// Do not wait for the child process to exit before 
// reading to the end of its redirected stream. 
// p.WaitForExit(); 
// Read the output stream first and then wait. 
string output = p.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 

但如果你想在后台行为,你就需要在后台线程执行StandardOutput.ReadToEnd(),然后创建一个机制从主控制台线程检索该输出,这看起来像很多工作,现在我可以想到任何优于PowerShell后台作业的优势。

另一种方法是创建一个运行空间来执行bg作业,因为此blog post by Jim Truher指出。

0

这不是优雅或有据可查。它创建一个System.Diagnostic.Process对象并对其执行一些常见的初始化。一旦获得Process对象,您可以对其执行其他调整,然后调用Process.Start来启动该过程。

function New-Process($cmd, $arguments, [switch]$stdout, [switch]$stdin, [switch]$stderr, [switch]$shellexec, [switch]$showwindow) 
{ 
    $process = New-Object "System.Diagnostics.Process" 
    $startinfo = New-Object "System.Diagnostics.ProcessStartInfo" 

    $startinfo.FileName = $cmd 
    $startinfo.Arguments = $arguments 
    $startinfo.WorkingDirectory = $pwd.Path 
    $startinfo.UseShellExecute = $shellexec 
    $startinfo.RedirectStandardInput = $stdin 
    $startinfo.RedirectStandardOutput = $stdout 
    $startinfo.RedirectStandardError = $stderr 

    if (!$showwindow) { 
     $startinfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden 
    } 

    $process.StartInfo = $startinfo 

    return $process 
} 
+0

如何执行powershell.exe来调用test1.ps1文件并将输出转换为日志? – Kiquenet 2012-09-07 08:05:19