2016-04-29 28 views
2

我想循環重複執行一個程序。Powershell啓動過程,等待超時,殺死並獲取退出代碼

有時,程序崩潰,所以我想殺了它,所以下一次迭代可以正確開始。我通過超時確定這一點。

我有超時工作,但無法獲得該程序的退出代碼,我也需要確定其結果。

之前,我並沒有等待超時,而是使用了 - 在Start-Process中等待,但是如果啓動的程序崩潰,這會使腳本掛起。有了這個設置,我可以正確地得到退出代碼。

我從ISE執行。

for ($i=0; $i -le $max_iterations; $i++) 
{ 
    $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru 
    # wait up to x seconds for normal termination 
    Wait-Process -Timeout 300 -Name $programname 
    # if not exited, kill process 
    if(!$proc.hasExited) { 
     echo "kill the process" 
     #$proc.Kill() <- not working if proc is crashed 
     Start-Process -filePath "taskkill.exe" -Wait -ArgumentList '/F', '/IM', $fullprogramname 
    } 
    # this is where I want to use exit code but it comes in empty 
    if ($proc.ExitCode -ne 0) { 
     # update internal error counters based on result 
    } 
} 

我怎樣才能

  1. 啓動一個進程
  2. 等待它的有序進行和完成
  3. 殺死它,如果它的崩潰(如打超時)
  4. 獲取退出代碼的過程
+0

【如何等待和殺死在PowerShell中的超時處理(HTTPS: //stackoverflow.com/q/19532998/995714) –

回答

5

您可以終止進程更多si mply使用$proc | kill$proc.Kill()。要知道,你將無法取回在這種情況下,退出代碼,您應該相當剛剛更新內部錯誤計數器:

for ($i=0; $i -le $max_iterations; $i++) 
{ 
    $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru 

    # keep track of timeout event 
    $timeouted = $null # reset any previously set timeout 

    # wait up to x seconds for normal termination 
    $proc | Wait-Process -Timeout 4 -ea 0 -ev timeouted 

    if ($timeouted) 
    { 
     # terminate the process 
     $proc | kill 

     # update internal error counter 
    } 
    elseif ($proc.ExitCode -ne 0) 
    { 
     # update internal error counter 
    } 
} 
+0

謝謝!等待進程在你的解決方案中等待正確的時間爲400秒,但是「#終止進程」子句在超時之後永遠不會打 - 也是這樣,進程永遠不會被終止,並且在下一次迭代之後,2個進程正在運行。 (我用一個小超時測試來強制這種情況。) –

+1

你說得對,我認爲Wait-Process會返回一些東西。我編輯了我的答案,現在我將錯誤消息分配給$超時,並且在發生超時的情況下,它被設置。 –

+0

謝謝! (有一個小錯字。)工作很好! –