How do I trap signals in PowerShell?

后端 未结 2 1487
醉话见心
醉话见心 2021-01-02 05:54

Is this possible? I\'ve finally decided to start setting up my personal .NET development environment to closer mimic how I\'d set up a *NIX dev environment, which means lear

相关标签:
2条回答
  • 2021-01-02 06:34

    This handles console kepboard input. If control C is pressed during the loop you'll have a chance to handle the event however you want. In the example code a warning is printed and the loop is exited.

    [console]::TreatControlCAsInput = $true
    dir -Recurse -Path C:\ | % {
        # Process file system object here...
        Write-Host $_.FullName
    
        # Check if ctrl+C was pressed and quit if so.
        if ([console]::KeyAvailable) {
            $key = [system.console]::readkey($true)
            if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C")) {
                Write-Warning "Quitting, user pressed control C..."
                break
            }
        }
    
    0 讨论(0)
  • 2021-01-02 06:45

    Do you mean something like this?

    try
    {
        Push-Location
        Set-Location "blah"
        # Do some stuff here
    }
    
    finally
    {
        Pop-Location
    }
    

    See documentation here. Particularly that paragraph: "The Finally block statements run regardless of whether the Try block encounters a terminating error. Windows PowerShell runs the Finally block before the script terminates or before the current block goes out of scope. 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."

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