【问题标题】:How to do some cleanup on a ctrl+break before the scripts ends如何在脚本结束之前对 ctrl+break 进行一些清理
【发布时间】:2021-07-30 04:32:06
【问题描述】:

我在脚本中使用 Start-Transcript 和 Stop-Transcript。问题是如果有人在 ISE 中使用 read button 进行 ctrl+break,或者只是在窗口中使用 ctrl+c。脚本结束,但 Stop-Transcript 永远不会被调用。这会锁定文件,我需要手动执行 Stop-Transcript 来解锁文件。

那么如何解决这个问题,即使在 ctrl+c 上,我也可以进行清理?

在 win32 中,我知道我可以注册一个被调用的函数,并且我可以做到这一点。

【问题讨论】:

标签: powershell


【解决方案1】:

您可以做的最简单的事情是实现 try、catch、finally:

Start-transcript
try{
   #your code here
}
catch{
    #all error end up here, if they are breaking errors
    Throw $_
}
finally{
    #this will run almost no matter what happens. even on break, errors and ctrl+c
    Stop-transcript
}

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多