2012-04-16 202 views
7

我得到這個消息,每次我的腳本不正確結束和停止成績單不執行:powershell - 如何檢查成績單是否正在運行?

Start-Transcript : Transcription has already been started. Use the stop-transcr 
ipt command to stop transcription. 
At C:\ps\003desifrovanie.ps1:4 char:17 
+ start-transcript <<<< -path c:\_LOG\sfrbdesifrovanie.log -append 
+ CategoryInfo   : NotSpecified: (:) [Start-Transcript], InvalidOpe 
rationException 
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Power 
Shell.Commands.StartTranscriptCommand 

是否可以檢查是否成績單運行和停止它的if-then在腳本的開始?或者如何在最後可靠地阻止它?謝謝

回答

7

那麼你的PowerShell腳本開始處的一個空的try-catch塊如何停止轉錄呢?

try{ 
    stop-transcript|out-null 
} 
catch [System.InvalidOperationException]{} 
+0

這很簡單,它適用於我!謝謝 – culter 2012-04-16 08:52:20

+0

感謝關於'Out-Null'的提示!這是'$ null'的好替代方案 – 2012-06-25 22:32:45

2

嘗試這裏提供的試驗錄製功能:http://poshcode.org/1500

if(Test-Transcribing) {Stop-Transcript} 
+0

這不適用於Powershell 4(也許更早),例外必須更改。 – svandragt 2014-08-22 12:47:53

6

豈不像這樣的工作?

try 
{ 
    Start-Transcript 
    # Do my stuff 
} 

finally 
{ 
    Stop-Transcript 
} 

從文檔: finally塊語句無論try塊是否遇到終止錯誤運行。 Windows PowerShell在腳本終止之前或當前塊超出範圍之前運行Finally塊。即使您使用CTRL + C停止腳本,如果Exit關鍵字停止Catch塊內的腳本,則還會運行Finally塊。

+0

感謝您選擇此cmdlet。我很確定它將在未來有所幫助。 – culter 2012-04-16 11:18:21

1
try { 
    Start-Transcript -path $myOutLog 

} catch { 

     stop-transcript 

     Start-Transcript -path $myOutLog 
} 
+2

你能否提供一些關於這段代碼在做什麼的解釋? – rayryeng 2014-12-01 18:29:30

+1

由於原始海報從未回答過,我會提供解釋。如果Start-Transcript已經啓動,將會拋出一個錯誤。上面的代碼首先嚐試開始轉錄。如果轉錄已經開始,它會捕獲錯誤,停止轉錄,然後再次啓動。這確保輸出被髮送到由_ $ myOutLog_指定的位置。儘管抓住特定的錯誤而不是所有的錯誤可能是更好的做法。然後'} catch {'行會變成'} catch [System.InvalidOperationException] {'。 – 2015-09-23 15:53:56

相關問題