Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

powershell - Handle keyboard interrupt, execute end block

I have a powershell function that processes a list of files. I use the begin, process and end blocks for this:

begin {
    # prepate some stuff
}
process {
    # process each file
}
end {
    # clean up
}

Now, when I hit Ctrl+C, the whole script just terminates right at the spot where it was. That’s not really a problem for the process part as that will only do permanent changes on the very last command.

I do however still want to execute what’s in the end block to clean it up a bit, and to print some statistics about the files that did manage to get processed.

Is there a clean way to catch keyboard interrupts, while keeping the begin/process/end structure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to do this would be to disable the processing of Ctrl-C as an interupt while your script block is running. You would have to manually check for it to break out of course but it should guarantee that the end block runs

begin { 
  [Console]::TreatControlCAsInput = $true
}
process {
  # Maybe check for Ctrl-C here to terminate processing
}
end { 
  [Console]::TreatControlCAsInput = $false
}

In order to check for Ctr-C as input in a non-blocking way you can do the following

if ([Console]::KeyAvailable) {
  $key = [Console]::ReadKey($true)
  if ($key.key -eq "C" -and $key.modifiers -eq "Control") { 
    # Clean up and exit
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...