gracefully exit from program spawned by powershell script

Viewed 29

Lets assume I have the following script:

$originalPath=pwd
D:\code\ps1\misc\title.ps1 "dynamo db"

$CURPATH = "$PSScriptRoot\path.txt"
$DB_DIR= cat $CURPATH

cd $DB_DIR
java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar
cd $originalPath

This script starts the java program correctly, however, when I hit CTRL+C, the last cd command is not executed.

Is this by design for powershell? Or can I change this?

1 Answers

Written as of PowerShell Core 7.2.5.

When you use Ctrl-C to abort an external program, the current PowerShell script (runspace) is terminated too.

While you cannot prevent your script from getting terminated, 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

}
Related