This answer applies up to at least PowerShell (Core) 7.3.5.
When you use Ctrl-C to abort an external program, the current PowerShell script (runspace) is invariably terminated too.
While you cannot generally prevent your script from getting terminated,[1] you can perform clean-up actions, namely in the finally
block of a try / catch / finally statement:
$originalPath = $PWD
# ...
try {
cd $DB_DIR
java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar
} finally {
# This block is *always* executed, but limitations apply
# if Ctrl-C was pressed:
# * Execution invariably ends with this block.
# * You cannot output to the success output stream or error stream,
# neither explicitly nor implicitly: doing so quietly and instantly
# aborts processing.
# * However, the *other* output streams *can* be targeted, namely with
# the following cmdlets (but note that except for Write-Host and Write-Warning,
# producing visible output is opt-in):
# Write-Host, Write-Warning, Write-Verbose, Write-Debug, Write-Information
cd $originalPath
}
请注意有关内容的限制输出流您可以定位,如上面的代码注释中所述,这源于finally
阻止在脚本终止过程的后期执行。
值得注意的是,尝试使用Write-Output
或隐式成功流输出或Write-Error
will 悄悄中止的执行finally
那时,而Write-Host
, Write-Verbose
and Write-Warning
仅举几个最重要的,可以安全使用。
[1] The only way to intercept Ctrl-C in order to prevent termination is via a custom keyboard-polling loop, after having set [Console]::TreatControlCAsInput = $false
- see this answer for an example.