Gracefully stopping in Powershell

試著忘記壹切 提交于 2019-11-27 14:27:44

问题


How do I catch and handle Ctrl+C in a PowerShell script? I understand that I can do this from a cmdlet in v2 by including an override for the Powershell.Stop() method, but I can't find an analog for use in scripts.

I'm currently performing cleanup via an end block, but I need to perform additional work when the script is canceled (as opposed to run to completion).


回答1:


You could use the method described on here on PoshCode

Summary:

Set

[console]::TreatControlCAsInput = $true

then poll for user input using

if($Host.UI.RawUI.KeyAvailable -and (3 -eq  
    [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))



回答2:


The documentation for try-catch-finally says:

A Finally block runs even if you use CTRL+C to stop the script. A Finally block also runs if an Exit keyword stops the script from within a Catch block.

See the following example. Run it and cancel it by pressing ctrl-c.

try
{
    while($true)
    {
        "Working.."
        Start-Sleep -Seconds 1
    }
}
finally
{
    write-host "Ended work."
}



回答3:


There is also a Stopping property on $PSCmdlet that can be used for this.



来源:https://stackoverflow.com/questions/1710698/gracefully-stopping-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!