Skip to content

$? doesn't change in case of parsing error #3798

Closed

Description

@dronkoff

Steps to reproduce

1..5 | buggy_call
$?

The result is $False and this is expected

1..5 | $_
$?

The result is $True and this is not expected

Expected behavior

1..5 | $_
$?

The result of $? should be $False because previous statement results in an error.

Environment data

PS C:\temp> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.296
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.296
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Notes

From Tom Nolan words:

The problem here is that $? Is set during the CheckActionPreference method when an error is encountered. https://github.com/PowerShell/PowerShell/blob/02b5f357a20e6dee9f8e60e3adb9025be3c94490/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs

However, CheckActionPreference is not executed until the AST has been parsed (https://github.com/PowerShell/PowerShell/blob/02b5f357a20e6dee9f8e60e3adb9025be3c94490/src/System.Management.Automation/engine/parser/Compiler.cs) and PowerShell actually attempts to execute the command, stepping through the pipeline.

Activity

  1. MaximoTrinidad commented on May 17, 2017

    @MaximoTrinidad

    At the same, this issue can be replicated in PowerShell Core (v6 Beta).

    posh_issue_2017-05-17_15-45-56

    Please, I may suggest to also post this incident at Windows PowerShell UserVoice site at: https://windowsserver.uservoice.com/forums/301869-powershell/category/148044-powershell-engine

    This way the Windows PowerShell team can assist in taking a look at this issue.

    :)

  2. BrucePay commented on May 17, 2017

    @BrucePay
    Collaborator

    PowerShell compiles the entire text of a script at once so a parse error anywhere in the block prevents the entire block from being executed. QED you can't catch or detect a parse error in the code being parsed since that code is never run. Michael Klement (@mklement0) 's example of 1/0 is not a parse error. (It was treated as a parse-time error in PowerShell V1 but it's been a runtime error since then.)

  3. added
    WG-Engine
    Issue-Discussion
    on May 18, 2017
  4. iSazonov commented on May 18, 2017

    @iSazonov
    Collaborator

    Really in second example a pipeline is created but interrupted and the code that set QuestionMarkVariableValue don't executed.
    Default value for QuestionMarkVariableValue is True - so we see True as result.

    I believe it is by design - (1) as Bruce Payette (@BrucePay) said it is not problem for script because no command will be executed - that's why we should use try-catch. (2) for interactive session using $? is pointless while you see parser error - I believe we shouldn't worry about QuestionMarkVariableValue value in that case.

  5. mklement0 commented on May 18, 2017

    @mklement0
    Contributor

    Ilya (@iSazonov): My bad (I have little insight into how PS parsing works at this point; other comment deleted too):

    I missed that if the code is placed in a script, the entire script won't be executed, so it is treated as parse error.

    Interactively, this can be shown by placing $? on the same line, in which case $? is never executed:

    1..5 | $_; $?   # $? never executes

    Calling a script that fails to parse from another script DOES set $? to $False, so the interactive behavior - though unexpected - is less of an issue, as you say.

    On a related note, however: from the calling script's perspective, shouldn't an attempt to call a script with parse errors result in a terminating error that the calling script must therefore handle with try / catch?

  6. iSazonov commented on May 18, 2017

    @iSazonov
    Collaborator

    Michael Klement (@mklement0) Please don't remove history. You can strike out - use double tildes around the words.

  7. iSazonov commented on May 18, 2017

    @iSazonov
    Collaborator

    My understanding is that $? is from v1 time and today a prefered way is try / catch

  8. mklement0 commented on May 18, 2017

    @mklement0
    Contributor

    Good point re history, will do.

    $? still has (and, I presume, will continue to have) its place for reflecting non-terminating errors, but a parse error is arguably severe enough to warrant a terminating one so that the calling script aborts by default.

    Yes, you can detect the parse error with try / catch (the exception inside the error record is of type [System.Management.Automation.ParseException]), but by default the calling script continues to run.

    Note that an ordinary non-terminating error - such as reported by Get-Item /Nosuch can not be caught with try / catch.

    From what I can tell, this problematic hybrid behavior - non-terminating-error behavior by default, terminating-error behavior with try / catch - applies to the following kinds of errors:

    • parse errors in an invoked script ([System.Management.Automation.ParseException])
    • runtime errors such as 1 / 0 ([System.Management.Automation.RuntimeException])
    • parameter-binding exceptions such as Get-Content -NoSuchParam ([System.Management.Automation.ParameterBindingException])
    • .NET methods that report an exception, such as[int]::Parse('foo') ([System.Management.Automation.MethodInvocationException])

    Note sure if there are more.

    As I've suggested in #3359 (comment), perhaps it makes more sense to treat these as terminating errors.

  9. iSazonov commented on May 18, 2017

    @iSazonov
    Collaborator

    In PowerShell context "terminating" error is a error "terminating current pipeline".
    As previously mentioned, we have confusion with terminating and non-terminating errors.

  10. rkeithhill commented on May 18, 2017

    @rkeithhill
    Collaborator

    My understanding is that $? is from v1 time and today a prefered way is try / catch

    $? is still useful in scripts to see if a command encountered a non-terminating error. Say I'm copying a bunch of files recursively from one dir to another. If there is a file or folder I don't have permission to the copy will not 100% succeed. I can test for this condition by checking $?.

    Of course, you can tell PowerShell to convert the non-terminating error to a terminating error with -ErrorAction Stop and then use try/catch. Which one a scripter chooses comes down to preference - what a scripter is more comfortable with.

  11. changed the title [-]&? doesn't change in case of parsing error[/-] [+]$? doesn't change in case of parsing error[/+] on May 18, 2017
  12. mklement0 commented on May 18, 2017

    @mklement0
    Contributor

    Keith Hill (@rkeithhill):

    Absolutely, but my point was that the error types I've mentioned (parse in callee/runtime/parameter binding/method invocation):

    • behave like non-terminating errors by default
    • though in their ability to be caught irrespective of the current $ErrorActionPreference value they behave like terminating ones - this is what I meant by "hybrid".

    It seems to me that making these error types regular terminating errors not only resolves the inconsistency, but also makes more sense:
    These types of errors are not the ones you want to tolerate as partial failures while the script goes on to still perform (partially) useful things.

    For instance, if I call Get-Content -NoSuchParameter in a script, I want that script to break by default.

    With respect to the general distinction between terminating and non-terminating errors and to what extent PS and its cmdlets play by the official rules, I've tried to summarize the state of affairs in this SO answer a while back.

    [Update with the benefit of hindsight: I was arguing for a script-terminating error, as opposed to a statement-terminating one; the former term is not official, but reflects the de-facto behavior summarized in this doc issue.]

  13. dronkoff commented on May 18, 2017

    @dronkoff
    Author
    $?  
       Contains the execution status of the last operation. It contains
       TRUE if the last operation succeeded and FALSE if it failed
    

    From the end user point of view it doesn't matter what type of error he sees on the screen. He sees red text and an error description but $? returns $true. He decides "ok, look like this thing doesn't work, I wont use it" and then he goes to:

    $error.Clear()
    ... -ErrorAction SilentlyContinue
    if($error.Count -gt 0) 

    Looks like it would be great to change the default value to $false.
    If no operation was executed then how status of it's execution can be $true.

  14. lzybkr commented on May 18, 2017

    @lzybkr
    Contributor

    I do question the value of making a change here. $? is most useful when it's not obvious if there was an error or not, and it's especially useful in automation.

    Parse errors that occur during automation should be exceedingly rare - it basically means you didn't test your script before deployment.

  15. 2 remaining items

  16. mklement0 commented on Mar 13, 2018

    @mklement0
    Contributor

    Bruce Payette (@BrucePay):

    Yes, but that's not what I meant. I was responding to the following comment by Jason Shirk (@lzybkr):

    it basically means you didn't test your script before deployment.

    What I was trying to say was: at runtime, an attempt to call a script that fails to parse should cause a script-terminating error (runspace-terminating error), not a statement-terminating error - whether in production or during development.

    It simply makes no sense to continue execution by default in such a scenario, which is what currently happens.

  17. BrucePay commented on Mar 14, 2018

    @BrucePay
    Collaborator

    Michael Klement (@mklement0) I get that parse errors feel different, but thinking practically, why should a parse error be handled differently from any other fatal error that the script might encounter? Either way, from the caller's perspective, it's just another command that failed. Now you could argue that all unhandled errors should be fatal and terminate the script by default. That's what C# effectively does. But that's not what shells (bash, cmd, etc.) do and PowerShell is a shell. But PowerShell is also a scripting language and so we have hybrid semantics with exit status ($?) and exceptions. In fact part of the reason for deciding to have the trap statement was that it made it easy to change how fatal errors are handled throughout a script.

    (Small note: you probably don't want syntax errors to be runspace terminating otherwise your interactive session would end the first time you mistyped a command. That seems undesirable :-)

  18. mklement0 commented on Mar 17, 2018

    @mklement0
    Contributor

    Bruce Payette (@BrucePay) I'll address the conceptual issues later; but re your small note:

    you probably don't want syntax errors to be runspace terminating otherwise your interactive session would end the first time you mistyped a command.

    Runspace-terminating errors don't terminate interactive sessions; I don't know how interactive sessions are implemented, but executing something like Throw "a fit" on the command line does not terminate the session.

  19. mklement0 commented on Mar 18, 2018

    @mklement0
    Contributor

    Bruce Payette (@BrucePay):

    I get that parse errors feel different, but thinking practically, why should a parse error be handled differently from any other fatal error that the script might encounter?

    Indeed, they should all be treated the same.

    Now you could argue that all unhandled errors should be fatal and terminate the script by default.

    Indeed, that's exactly what should happen (needless to say, a massively breaking change, but hopefully at least food for thought for when the time comes).

    But that's not what shells (bash, cmd, etc.) do and PowerShell is a shell.

    PowerShell is also a shell, but its scripting language is miles above Bash's tacked-on language, let alone cmd.exe's.

    Given that it has the capabilities of a "normal" programming language and borrows many of its constructs (including try / catch), making terminating errors terminate the script, by default (making them fatal) would have been a great opportunity to make scripting "grow up".

    I don't think that anyone would have complained about this helpful deviation from the brittle Bash behavior.

    part of the reason for deciding to have the trap statement was that it made it easy to change how fatal errors are handled throughout a script.

    Defaults matter greatly, and having to trap something - including remembering to place a break in the script block - in order to achieve what should have been the default behavior is unfortunate.

    A reversal of this logic would have been great: let a terminating error terminate the script by default, and allow an optional trap statement to prevent that or modify the exit.

  20. BrucePay commented on Apr 24, 2018

    @BrucePay
    Collaborator

    Michael Klement (@mklement0)

    Now you could argue that all unhandled errors should be fatal and terminate the script by default.

    Indeed, that's exactly what should happen

    Think about that for a second. There are a lot of little errors where people just let the error message go to the output stream, Instead you want these errors to terminate the entire thread of execution? If nothing else, it would make the interactive experience unusable.

    Runspace-terminating errors don't terminate interactive sessions; I don't know how interactive sessions are implemented, but executing something like Throw "a fit" on the command line does not terminate the session.

    Runspace terminating errors most certainly terminate your session since a session is nothing but a wrapper around a runspace. Your example

    Throw "a fit" 
    

    is not a runspace terminating exception. It's just an exception that will, if uncaught, terminate the current thread of execution. The runspace, however, will remain open (i.e. not terminated). If you do want to try terminating you runspace, fell free to try

    [runspace]::defaultrunspace.close()
    
  21. mklement0 commented on Apr 24, 2018

    @mklement0
    Contributor

    Bruce Payette (@BrucePay):

    It's just an exception that will, if uncaught, terminate the current thread of execution.

    In the absence of information in the documentation, I've been struggling to come up with the right terminology to describe the unit of execution that gets terminated when you execute something like Throw "a fit" - I've called it a script-terminating error and then, sensing it might not be the best term, guessed at runspace-terminating error.

    Based on what you're saying, the most accurate term is therefore thread-terminating error?
    Until I have confirmation, I'll call them fatal errors - which may be the more intuitive term anyway (which would still leaves us with the potentially misleading term terminating error in the existing documentation, where it more often than not means statement-terminating error).
    Do tell us what you think the term should be.


    Therefore, what I was really advocating was to treat cases such as 1 / 0 and [int]::Parse('foo') the same as Throw "a fit", i.e., to treat them as fatal errors (by default).

    In other words: yes, inside a script, I want that script to terminate with an error by default in all these cases.

  22. BrucePay commented on Apr 24, 2018

    @BrucePay
    Collaborator

    I've called it a script-terminating error and then, sensing it might not be the best term,

    Script-terminating is generally fine. Or "terminates the current thread of execution".

    Therefore, what I was really advocating was to treat cases such as 1 / 0 and [int]::Parse('foo') the same as Throw "a fit", i.e., to treat them as fatal errors (by default).

    That's easy - put a trap at the top level of your script:

    trap { break }
    & {
        &{
            foreach ($i in 0..5)
            {
                1/$i
                "Hello"
            }
        }
    }
    

    This will turn statement-terminating error into a "fatal" one.

  23. mklement0 commented on Apr 24, 2018

    @mklement0
    Contributor

    Bruce Payette (@BrucePay):

    Script-terminating is generally fine. Or "terminates the current thread of execution".

    Thanks. I've since kind of fallen in love with fatal error for its brevity, though (a fatal attraction, if you will), so it may leak out from time to time. Let me know if you think that's not appropriate.

    (My original rationale for coining the term script-terminating was to (a) use a term for the unit of execution being terminated familiar to even casual PowerShell users and (b) to keep the word "terminating" in there so as tease out the difference between a statement-terminating and a thread-terminating error so conspicuously absent from the documentation. It doesn't tell the fully story, however - but perhaps it doesn't need to.)

    Yes, your trap { break } solution effectively does what I'm asking for, but my point is that this should always have been the default behavior - but I know that that only matters in the context of the "PowerShell vZeroTechnicalDebt" conversation.

  24. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  25. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  26. added
    Resolution-No Activity
    on Nov 16, 2023
  27. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  28. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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-DiscussionResolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions