powershell - 如何检查transcript是否正在运行?

cul*_*ter 10 powershell powershell-2.0

每当我的脚本没有正确结束并且没有执行stop-transcript时,我会收到此消息:

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
Run Code Online (Sandbox Code Playgroud)

是否可以检查脚本是否正在运行并使用if-then在脚本开始时停止?或者如何在结束时可靠地阻止它?谢谢

Oca*_*tal 10

try-catch你的powershell脚本开头的空块怎么样才能停止转录?

try{
  stop-transcript|out-null
}
catch [System.InvalidOperationException]{}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ant 7

不会像这样的工作吗?

try
{
    Start-Transcript
    # Do my stuff
}

finally
{
    Stop-Transcript
}
Run Code Online (Sandbox Code Playgroud)

从文档:无论Try块是否遇到终止错误,Finally块语句都会运行.Windows PowerShell在脚本终止之前或当前块超出范围之前运行Finally块.即使您使用CTRL+C来停止脚本,也会运行Finally块.如果Exit关键字从Catch块中停止脚本,则也会运行Finally块.