Skip to content

Should we detect/Deny using $_ as a user defined variable? #3695

Closed

Description

This works but it seems like terrible practice - should we detect/deny using $_ as a user defined variable?
(At PSCONF.EU and a customer's colleague is doing this in his code)

foreach ($_ in gps | where {$.name -like "*SS"})
{
$
.name
}

This also works:

$_ = "test"
write-host -ForegroundColor red "Thiis is a $_ "

Activity

  1. added
    WG-Language
    Issue-Discussion
    on May 4, 2017
  2. AdilHindistan commented on May 4, 2017

    @AdilHindistan

    Happen to know why they were doing it? Does not seem to serve any purpose other than potentially creating a hell of a confusion.

  3. lfshr commented on May 5, 2017

    @lfshr

    Since it's doable, but bad practice, maybe a PSScriptAnalyzer rule instead? What about the risk of breaking code that's already out in the wild?

  4. added
    Breaking-Change
    on May 5, 2017
  5. jpsnover commented on May 8, 2017

    @jpsnover
    ContributorAuthor

    My understanding was that it was a beginner so it was just bad practice.

  6. jpsnover commented on May 8, 2017

    @jpsnover
    ContributorAuthor

    Chances are that if they are setting $_ or $PSITem, they either already have every brittle code or it might already be broken code.

  7. mklement0 commented on May 9, 2017

    @mklement0
    Contributor

    #3061 is a related issue for all automatic variables.

    There are 28 in total that shouldn't be writable, but currently are.

    As for $_ / $PSItem specifically (I agree that it shouldn't be assignable - or perhaps just in this one scenario):

    The need to specify a variable explicitly in the foreach statement allows for a more descriptive name than the implicit $_ can provide in the ForEach-Object case, but I can see how someone would choose $_ - either by analogy with or due to confusion with ForEach-Object.

    It is the built-in foreach alias that has sown perennial confusion between the ForEach-Object cmdlet and the foreach language statement.

  8. lfshr commented on May 9, 2017

    @lfshr

    It may be okay if the failure happens during parsing stage. As long as a previously working script doesn't fail half way through. And I suppose scripts breaking should be a risk when upgrading PS. I agree that these should be read-only, and if you listened to people like me nothing would ever move forward! 😛
    I also think that if they are going to be read-only then in this case they should be read-only regardless of strict mode. Thoughts?

  9. iSazonov commented on May 9, 2017

    @iSazonov
    Collaborator

    We discussed aliases previously in #2000 and PowerShell PG agreed that aliases useful only in interactive mode and we need to write RFC originally relying on using (yes! - it is in parsing time). Welcome to https://github.com/PowerShell/PowerShell-RFC/!

  10. mklement0 commented on May 19, 2017

    @mklement0
    Contributor

    I've just submitted #3830, which, if implemented, would be a way of:

    • mitigating the foreach / ForEach-Object confusion and allowing their peaceful coexistence,
    • while still allowing the advisable prevention of explicit assignments to automatic variables such as $_ .
  11. nightroman commented on Jul 17, 2017

    @nightroman

    Adil Hindistan (@AdilHindistan)

    Happen to know why they were doing it? Does not seem to serve any purpose other than potentially creating a hell of a confusion.

    I often convert ForEeach-Object to foreach loop both ways. It is convenient to use the same variable $_ and keep the processing blocks not changed. To me, it is not confusion but rather clarity, when I see $_ in my code I know it is the current loop/pipeline variable, no matter what surrounds it.

  12. mklement0 commented on Jul 17, 2017

    @mklement0
    Contributor

    Roman Kuzmin 1967-2026 (@nightroman)

    I do understand the appeal of the consistent use of $_, but, I think it is generally problematic to allow assigning to automatic variables (although in this particular case, making the variable read-only would probably be too much of a breaking change).

    The solution, I think, is to let PowerShell define $_ implicitly, as it does for ForEach-Object, if no loop variable is specified, as I've proposed in #3830.

    Applied to the command in the initial post:

    Instead of:

    foreach ($_ in gps | where {$.name -like "*SS"}) { $_.name }

    we could write:

    # Not defining a loop variable ($var in ...) could implicitly define $_
    foreach (gps | where {$.name -like "*SS"}) { $_.name }
  13. added
    Review - Committee
    on Jul 18, 2017
  14. 43 remaining items

  15. SeeminglyScience commented on Aug 16, 2017

    @SeeminglyScience
    Contributor

    Another example of using $_ is the Find-Ast function in PowerShellEditorServices. A couple of things to note:

    1. It doesn't use the method described in this thread. But, if I had known about it at the time I would have considered it for the 3.0 compatible portion if it let me avoid recreating the ScriptBlock in the module scope.

    2. For PS 4.0+ it uses an existing public API that will not be broken by the proposed change. ScriptBlock.InvokeWithContext pulls _, input, and this out of variablesToDefine and passes them directly to InvokeWithPipe.

    All of that said, I don't see why this needs to be more than a PSSA warning. I think that making them read only is unnecessary and potentially harmful for little gain. And blocking it completely with a parse exception just seems way over the top.

  16. Jawz84 commented on Aug 17, 2017

    @Jawz84
    Contributor

    Considering all of the discussion above, i'd like to vote for a PSSA warning only. The argument that this will not be shown in non PSSA editors, holds. Yet I don't see which threat is mitigated by restricting use of $_. I think many devs like Posh for its flexibility. Let's keep that flexibility.

  17. iSazonov commented on Aug 17, 2017

    @iSazonov
    Collaborator

    I am not PowerShell/powershell-committee Team member so I can only give my understanding of the conclusion.

    For personal using - Writing to $_ is bad practice in most cases and we do not wish to encourage such practices. In most cases, there are native workarounds that Michael Klement (@mklement0) has demonstrated more than once. (Some may continue to use Windows PowerShell only but over time I'm sure they'll like PowerShell Core too)

    For tools - There are tools/modules that use custom $_ . Sometimes it's also just a bad style. Sometimes this is forced to be used because there are no native alternatives. In any case, we want to preserve backward compatibility as much as possible. To do that, we can use a strict mode, lexical strict mode and Interop-Module.

    For "special things" - Right way is to use native things. Currently PowerShell is Open Source and Community is free to implement natively things that have long been expected - Concurrency, DSL
    (Did you know we already have a pilot implementation in #3169?), also we have plans to enhance classes and finally, Jason Shirk (@lzybkr) proposal "to make public the API that allows setting $_ when invoking a script block."
    No doubts, all the popular packages mentioned above and not mentioned at all will have many benefits if such fundamental things are implemented natively in PowerShell Core. We don't want to force you to port the modules - they must continue to work, but their new versions will have these new benefits. We very much hope that you will actively participate in this work starting now.

  18. added
    Review - Committee
    and removed
    Committee-Reviewed
    on Aug 22, 2017
  19. joeyaiello commented on Aug 22, 2017

    @joeyaiello
    Contributor

    As discussed on Twitter, putting this back up for review given the feedback so far.

  20. bergmeister commented on Aug 22, 2017

    @bergmeister
    Contributor

    My 2 cents as a PowerShell user:
    I definitely discourage re-purposing internal variables such as $_. If some 3rd party PowerShell script would start to break in a new version of Windows PowerShell then I'd be very upset but if I had to check my scripts and their 3rd party dependencies anyway when swiching to PowerShell Core then I would not mind it as it would be expected to have some breaking changes. The only risk would be if my testing would not invoke this 'naughty' code path so that I would not spot it. I guess most users would check portability only very loosely by testing if they can still import their modules and maybe executing it once through the main execution path.

    To compare it to other scripting languages: Matlab allows re-purposing of variables defined by it such as pi and even the imaginary variable i but it can easily lead to unintended behaviour when using e.g. i as a loop variable.

  21. iSazonov commented on Aug 23, 2017

    @iSazonov
    Collaborator

    Before RTM we should review all breaking changes and try to fix it in interop module.

  22. joeyaiello commented on Aug 23, 2017

    @joeyaiello
    Contributor

    We just spoke amongst @PowerShell/powershell-committee, and we've decided to go with your feedback:

    • make no changes in the engine to avoid breaking anyone
    • VS Code (or other PS Editor Services-enabled editors) will be the dominant editing platform for 6.0, and so we can create a useful rule that throws whenever someone assigns a value to $_ (or any of the others that Michael Klement (@mklement0) enumerated)
  23. added
    Committee-Reviewed
    and removed
    Review - Committee
    on Aug 23, 2017
  24. added
    Resolution-Won't Fix
    on Aug 23, 2017
  25. iSazonov commented on Aug 24, 2017

    @iSazonov
    Collaborator

    Is there a tracking Issue in VS Code repo?

    For PSScriptAnalyzer PowerShell/PSScriptAnalyzer#712

  26. SteveL-MSFT commented on Aug 24, 2017

    @SteveL-MSFT
    Member

    No VSCode issue needed. Once ScriptAnalyzer rule is created, it'll be used by EditorServices and automatically lights up in VSCode (and any other editor integrated with EditorServices)

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

    Breaking-ChangeCommittee-ReviewedIssue-DiscussionResolution-Won't FixWG-Language

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions