在PowerShell脚本中,我想制作脚本对Start-Transcript
所做的任何事情的记录。但是,有时脚本失败,并且脚本已经在运行。在这种情况下,会抛出错误,我无法找到避免该错误的方法。 我可以做些什么才能安全地启动成绩单?
如果成绩单已在运行,我想简单地停止并开始新的成绩单。
错误可以通过故意开始两个成绩单来再现。请记住,在现实生活中,上一次运行的脚本已经打开了成绩单。
错误情况
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 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
答案 0 :(得分:1)
所以,我在PS 5.0上的所有测试(这是我目前唯一可以访问的)显示,使用相同的输出文件名再次启动脚本会抛出你提到的错误,但也会停止脚本。之后手动试图阻止它会告诉我The host is not currently transcribing
。
所以,我认为您可以使用try catch方法来抑制错误:
Try{Start-transcript C:\transcript.txt -ErrorAction Stop}catch{Start-Transcript C:\transcript.txt}