Functional Code
This will give you the behaviour I believe you're after:
Try {
While($True) {
echo "looping"
Start-Sleep 3
}
} Finally {
Write-Host "goodbye!"
pause
}
References
Write-Output/echo - Synopsis
Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.
Write-Host - Synopsis
Writes customized output to a host.
Try-Catch-Finally - Syntax note
Note that pressing CTRL+C stops the pipeline. Objects that are sent to the pipeline will not be displayed as output. Therefore, if you include a statement to be displayed, such as "Finally block has run", it will not be displayed after you press CTRL+C, even if the Finally block ran.
Explanation
The key, as per TheIncorrigible1's comment and Vesper's answer is that the pipeline is stopped. But this is not because of an error in Write-Output
. And I don't find it is a satisfying explanation on its own.
- "If the command is the last command in the pipeline, the objects are displayed in the console." - appears this statement is false within a finally block. However, passing to
Out-Host
explicitly will yield desired output.
- On Try-Catch-Finally note
- The quoted section is confusing as it applies to unhandled objects sent to the pipeline.
- Objects sent to the pipeline and handled within a
Finally
block are fine.
- It talks about "even if the Finally block has ran" but the
pause
does not run if preceded by a Write-Output
.
More Code
A few things ran in the Finally
block to investigate behaviour, with comments as to what happens.
} Finally {
Write-Output "goodbye!" | Out-Default # works fine
pause
}
} Finally {
Write-Output "goodbye!" | Out-Host # works fine
pause
}
} Finally {
pause # works fine
Write-output "goodbye!" # not executed
}
} Finally {
try{
Write-Output "goodbye!" -ErrorAction Stop
}catch{
Write-Host "error caught" # this is not executed.
} # $error[0] after script execution is empty
pause
}
} Finally {
try{
ThisCommandDoesNotExist
}catch{
Write-Host "error caught" # this is executed
} # $error[0] contains CommandNotFoundException
pause
}