2017-10-11 175 views
0

在PowerShell脚本中,我想用Start-Transcript来编写任何脚本的脚本。但是,有时脚本失败了,并且脚本已经在运行。在这种情况下会引发错误,我找不到避免该错误的方法。 我能做些什么来防故障启动一个成绩单?PowerShell在脚本已经运行时的脚本错误

如果转录本已经在运行,我想停止它并开始一个新的。

可以通过故意启动两个转录本来复制错误。请记住,在现实生活中,以前的脚本运行已经让记录打开了。

错误情况

PS C:\> Start-Transcript c:\test.txt # pretend that this is a transcript which was not stopped properly by a previous script 

Transcript started, output file is c:\test.txt 

PS C:\> Start-Transcript c:\test.txt 
Start-Transcript : Transcription cannot be started. 
At line:1 char:1 
+ Start-Transcript c:\test.txt 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException 
    + FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand 

忽略与-ErrorAction SilentlyContinue不起作用!

PS C:\> Start-Transcript c:\test.txt # pretend that this is a transcript which was not stopped properly by a previous script 
Transcript started, output file is c:\test.txt 

PS C:\> Start-Transcript c:\test.txt -ErrorAction SilentlyContinue 
Start-Transcript : Transcription cannot be started. 
At line:1 char:1 
+ Start-Transcript c:\test.txt -ErrorAction SilentlyContinue 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException 
    + FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand 

停止谈话开始失败之前,如果成绩单不上PS 5.0(这是唯一一个我在有访问运行

PS C:\> Start-Transcript c:\test.txt 
Transcript started, output file is c:\test.txt 

PS C:\> Stop-Transcript # pretend that this is a transcript which was not stopped properly by a previous script 
Transcript stopped, output file is C:\test.txt 

PS C:\> Stop-Transcript 
Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing. 
At line:1 char:1 
+ Stop-Transcript 
+ ~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException 
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand 

回答

1

所以,我的所有测试时刻)显示,再次使用相同的输出文件名启动转录本会抛出您提到的错误,但也会停止转录。手动试图阻止它后会告诉我,The host is not currently transcribing

所以,我认为你可以使用尝试捕捉方法来取消错误:

Try{Start-transcript C:\transcript.txt -ErrorAction Stop}catch{Start-Transcript C:\transcript.txt}