Handle keyboard interrupt, execute end block

I have a powershell function that processes a list of files. For this, I use blocks begin, processand end:

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

Now that I hit Ctrl+C, the whole script just ends right where it was. This is not a problem for part of the process, as it will only make permanent changes to the most recent team.

However, I still want to execute whats in the block endin order to clean it up a bit and print some statistics about the files that were processed.

Is there a clean way to catch keyboard interrupts while maintaining a start / process / end structure?

+4
source share
2 answers

- Ctrl-C interupt, script. , , ,

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

, Ctr-C ,

if ([Console]::KeyAvailable) {
  $key = [Console]::ReadKey($true)
  if ($key.key -eq "C" -and $key.modifiers -eq "Contorl") { 
    ...
  }
}
+2

"finally" try/catch/finally - , script - :

  • Ctrl + C ( )
  • Exit catch
  • ( "finally" )

. , (: finally ).

( : - , / .

try { # begin, and/or process
}
catch { # optionally handle errors
}
finally { # clean up 
}

"", - , "" "", "" .

-1

All Articles