Gracefully stopping in Powershell

后端 未结 3 2023
逝去的感伤
逝去的感伤 2020-12-15 03:33

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 Pow

相关标签:
3条回答
  • 2020-12-15 04:14

    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))
    
    0 讨论(0)
  • 2020-12-15 04:16

    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."
    }
    
    0 讨论(0)
  • 2020-12-15 04:23

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

    0 讨论(0)
提交回复
热议问题