Skip to content

Redirection of stderr output from external programs sets $? invariably to $false, no longer reflecting whether $LASTEXITCODE equals 0 #10512

Closed

Description

Closely related: #4002

Normally, immediately after execution of an external program, $? and $LASTEXITCODE -eq 0 can be used interchangeably to test for success.

However, under the following conditions $? is invariably set to $false, even if $LASTEXITCODE contains 0 and therefore indicates success:

  • If a 2> or *> redirection is involved
  • and actual stderr output is produced by the external program.

Note that you generally cannot and shouldn't infer success vs. failure of an external program from the presence of stderr output - many CLIs use stderr to emit status information; only the process exit code should be consulted.

Steps to reproduce

Run the following on Windows, which produces both stderr and stdout output and reports 0 as the process exit code:

& { cmd /c 'nosuch & ver' *>$null; $?; $LASTEXITCODE } | Should -Be $true, 0

Expected behavior

The test should succeed.

Actual behavior

The test fails:

Expected @($true, 0), but got @($false, 0).

That is, $? was $false, even though $LASTEXITCODE was 0.

Environment data

PowerShell Core 7.0.0-preview.3
Windows PowerShell v5.1.18362.145

Activity

  1. added
    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get a
    on Sep 11, 2019
  2. mklement0 commented on Aug 2, 2020

    @mklement0
    ContributorAuthor

    Closed in favor of #3996 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get a

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions