When the script is executing the Read-Host
cmdlet, closing the window does not activate the finally
block. Below is an arbitrary but minimally functional example. I'm using PowerShell 5.0. The Beep() is just to make it obvious the finally block executes.
try {
$value= Read-Host -Prompt "Input"
sleep 5
} finally {
[Console]::Beep(880,1000)
}
- If you close the window by clicking the red X during the
Read-Host
thefinally
block will NOT execute. - If you close the window by clicking the red X during the
sleep
thefinally
block WILL execute. - If you interrupt with Ctrl-C at any point, the
finally
block WILL execute.
Is there something fundamental I'm missing about why the finally
block is NOT executing when closing the window during a Read-Host
?
The full case involves starting a service on an Amazon Snowball device and needing to stop the service if the script is closed. The full case behavior mirrors the example case above.
EDIT: Changed variable from $input to $value due to comments saying $input is a reserved variable. Does not change behavior.