处理键盘中断,执行结束块 [英] Handle keyboard interrupt, execute end block

查看:42
本文介绍了处理键盘中断,执行结束块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理文件列表的 powershell 函数.我为此使用了 beginprocessend 块:

I have a powershell function that processes a list of files. I use the begin, process and end blocks for this:

begin {
    # prepate some stuff
}
process {
    # process each file
}
end {
    # clean up
}

现在,当我按下 Ctrl+C 时,整个脚本就在原处终止.这对于流程部分来说并不是真正的问题,因为它只会对最后一个命令进行永久性更改.

Now, when I hit Ctrl+C, the whole script just terminates right at the spot where it was. That’s not really a problem for the process part as that will only do permanent changes on the very last command.

但是我仍然想执行 end 块中的内容来清理它,并打印一些关于设法处理的文件的统计信息.

I do however still want to execute what’s in the end block to clean it up a bit, and to print some statistics about the files that did manage to get processed.

有没有一种干净的方法来捕获键盘中断,同时保持开始/进程/结束结构?

Is there a clean way to catch keyboard interrupts, while keeping the begin/process/end structure?

推荐答案

一种方法是在脚本块运行时禁用 Ctrl-C 作为中断的处理.您当然必须手动检查它是否会中断,但它应该保证结束块运行

One way to do this would be to disable the processing of Ctrl-C as an interupt while your script block is running. You would have to manually check for it to break out of course but it should guarantee that the end block runs

begin { 
  [Console]::TreatControlCAsInput = $true
}
process {
  # Maybe check for Ctrl-C here to terminate processing
}
end { 
  [Console]::TreatControlCAsInput = $false
}

为了以非阻塞方式检查 Ctr-C 作为输入,您可以执行以下操作

In order to check for Ctr-C as input in a non-blocking way you can do the following

if ([Console]::KeyAvailable) {
  $key = [Console]::ReadKey($true)
  if ($key.key -eq "C" -and $key.modifiers -eq "Control") { 
    # Clean up and exit
  }
}

这篇关于处理键盘中断,执行结束块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆