Skip to content

PS should reset $? to the value it had when it entered the debugger #9474

@KirkMunro

Description

@KirkMunro

While a debugger is meant to allow you to modify variables, and otherwise debug and tinker with a program, the $? variable is a special case and its value should be preserved unless it is explicitly modified with an assignment command because PowerShell itself modifies that variable with any successful command that is invoked.

Steps to reproduce

Push-Location -LiteralPath $env:USERPROFILE
[Environment]::CurrentDirectory = $env:USERPROFILE
${FileSystem::.\test.ps1} = @'
Get-Process -id 12345678
if (-not $?) {
    'The value of $? was preserved during debugging.'
} else {
    'The value of $? was changed to $true during debugging.'
}
'@
$bp = Set-PSBreakPoint -Script .\test.ps1 -Line 2
& .\test.ps1
Remove-PSBreakpoint -Breakpoint $bp
Remove-Item .\test.ps1
Pop-Location

At this point you will be in the debugger on the breakpoint. Invoke the following command:

$?

You'll see that $? has a value of $false; however, since you invoked a command that was successful (i.e. that returned an exit code of 0), $? is now set to true. Invoke c to continue the script to allow it to run to completion.

Expected behavior

The script outputs the following statement:

The value of $? was preserved during debugging.

Actual behavior

The script outputs the following statement:

The value of $? was changed to $true during debugging.

Environment data

Name                           Value
----                           -----
PSVersion                      6.2.0
PSEdition                      Core
GitCommitId                    6.2.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

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 aResolution-FixedThe issue is fixed.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions