Skip to content

Attempts to write to the success or error output streams in a finally block cause instant, quiet termination, skipping remaining statements in the block #19988

@mklement0

Description

@mklement0

Prerequisites

Steps to reproduce

An attempt to write to the success output stream or the error output stream isn't just ignored in a finally block (see below for the documentation angle), it apparently quietly aborts further processing, meaning that any subsequent statements in the finally block do not execute.

# Run and press Ctrl-C when prompted.
Remove-Item -ErrorAction Ignore temp:/$PID.txt
try {
  Read-Host 'Press Ctrl-C now'
}
finally {
  # !! This attempt to write to the success output stream (pipeline) quietly aborts the entire block.
  "Aborted."  # ditto for Write-Error, but NOT for other Write-* cmdlets (other output streams), which generally work.
  Get-Date > temp:/$PID.txt
}

Note: On Windows, even code that does not write to the success / error streams can fail intermittently if Ctrl+C is pressed while Read-Host is prompting the user - see #19987


Fundamentally, it's worth clarifying - and documenting - what the precise constraints are on the statements that may be placed in a finally block:

  • about_Try_Catch_Finally currently only mentions that output to the success output stream (pipeline) doesn't work:

    • Objects that are sent to the pipeline will not be displayed as output.

    • In practice, the same goes for output to the error stream.

    • As discussed above, it isn't just that such output attempts are ignored - they actually abort further processing.

Expected behavior

Running Get-Content temp:/$PID.txt afterwards should print the timestamp when Ctrl-C was pressed.

Actual behavior

File temp:/$PID.txt is never created, so the Get-Content call fails.

Error details

No response

Environment data

PowerShell 7.4.0-preview.4

Visuals

No response

Metadata

Metadata

Assignees

Labels

KeepOpenThe bot will ignore these and not auto-closeNeeds-InvestigationThe behavior reported in the issue is unexpected and needs further investigation.WG-Enginecore PowerShell engine, interpreter, and runtime

Type

No type

Projects

Status

Issue Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions