How do I trap signals in PowerShell?

后端 未结 2 1488
醉话见心
醉话见心 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
            }
        }
    

提交回复
热议问题