35

如何在 PowerShell 脚本中捕获和处理Ctrl+ ?C我知道我可以从 v2 中的 cmdlet 中通过包含该Powershell.Stop()方法的覆盖来执行此操作,但我找不到在脚本中使用的模拟。

我目前正在通过endblock执行清理,但是当脚本被取消时我需要执行额外的工作(而不是运行完成)。

4

4 回答 4

66

try-catch-finally的文档说:

即使您使用 CTRL+C 停止脚本,Finally 块也会运行。如果 Exit 关键字从 Catch 块中停止脚本,Finally 块也会运行。

请参阅以下示例。运行它并按 取消它ctrl-c

try
{
    while($true)
    {
        "Working.."
        Start-Sleep -Seconds 1
    }
}
finally
{
    write-host "Ended work."
}
于 2013-04-03T13:40:37.803 回答
12

您可以在 PoshCode 上使用此处描述的方法

概括:

[console]::TreatControlCAsInput = $true

然后使用轮询用户输入

if($Host.UI.RawUI.KeyAvailable -and (3 -eq  
    [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
于 2009-11-24T13:04:58.923 回答
2

还有一个Stopping属性$PSCmdlet可以用于此。

于 2017-07-22T09:37:31.703 回答
0

这是最近的工作解决方案。我在需要控制执行中断(关闭文件句柄)的循环中使用 if 部分。

    [Console]::TreatControlCAsInput = $true # at beginning of script

    if ([Console]::KeyAvailable){

        $readkey = [Console]::ReadKey($true)

        if ($readkey.Modifiers -eq "Control" -and $readkey.Key -eq "C"){                
            # tasks before exit here...
            return
        }

    }

另请注意,有一个错误导致 KeyAvailable 在脚本启动时为真。您可以通过在开始时读取调用 ReadKey 来缓解。这种方法不需要,只是在这种情况下值得了解。

于 2021-12-21T21:26:59.700 回答