2010-07-07 56 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