You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Should we detect/Deny using $_ as a user defined variable? #3695
Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-Won't FixThe issue won't be fixed, possibly due to compatibility reason.WG-Languageparser, language semantics
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 $_ "
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 foreachstatement 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 foreachalias that has sown perennial confusion between the ForEach-Objectcmdlet and the foreachlanguage statement.
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?
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/!
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.
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.
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.
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.
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.
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.
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.
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)
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)
Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-Won't FixThe issue won't be fixed, possibly due to compatibility reason.WG-Languageparser, language semantics
Activity
AdilHindistan commentedon May 4, 2017
Happen to know why they were doing it? Does not seem to serve any purpose other than potentially creating a hell of a confusion.
lfshr commentedon May 5, 2017
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?
jpsnover commentedon May 8, 2017
My understanding was that it was a beginner so it was just bad practice.
jpsnover commentedon May 8, 2017
Chances are that if they are setting $_ or $PSITem, they either already have every brittle code or it might already be broken code.
mklement0 commentedon May 9, 2017
#3061 is a related issue for all automatic variables.
There are 28 in total that shouldn't be writable, but currently are.
As for
$_/$PSItemspecifically (I agree that it shouldn't be assignable - or perhaps just in this one scenario):The need to specify a variable explicitly in the
foreachstatement allows for a more descriptive name than the implicit$_can provide in theForEach-Objectcase, but I can see how someone would choose$_- either by analogy with or due to confusion withForEach-Object.It is the built-in
foreachalias that has sown perennial confusion between theForEach-Objectcmdlet and theforeachlanguage statement.lfshr commentedon May 9, 2017
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?
iSazonov commentedon May 9, 2017
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/!mklement0 commentedon May 19, 2017
I've just submitted #3830, which, if implemented, would be a way of:
foreach/ForEach-Objectconfusion and allowing their peaceful coexistence,$_.nightroman commentedon Jul 17, 2017
Adil Hindistan (@AdilHindistan)
I often convert
ForEeach-Objecttoforeachloop 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.mklement0 commentedon Jul 17, 2017
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 forForEach-Object, if no loop variable is specified, as I've proposed in #3830.Applied to the command in the initial post:
Instead of:
we could write:
43 remaining items
SeeminglyScience commentedon Aug 16, 2017
Another example of using
$_is the Find-Ast function in PowerShellEditorServices. A couple of things to note: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
ScriptBlockin the module scope.For PS 4.0+ it uses an existing public API that will not be broken by the proposed change.
ScriptBlock.InvokeWithContextpulls_,input, andthisout ofvariablesToDefineand passes them directly toInvokeWithPipe.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.
Jawz84 commentedon Aug 17, 2017
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.
iSazonov commentedon Aug 17, 2017
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.
joeyaiello commentedon Aug 22, 2017
As discussed on Twitter, putting this back up for review given the feedback so far.
bergmeister commentedon Aug 22, 2017
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:
Matlaballows re-purposing of variables defined by it such aspiand even the imaginary variableibut it can easily lead to unintended behaviour when using e.g.ias a loop variable.iSazonov commentedon Aug 23, 2017
Before RTM we should review all breaking changes and try to fix it in interop module.
joeyaiello commentedon Aug 23, 2017
We just spoke amongst @PowerShell/powershell-committee, and we've decided to go with your feedback:
$_(or any of the others that Michael Klement (@mklement0) enumerated)iSazonov commentedon Aug 24, 2017
Is there a tracking Issue in VS Code repo?
For PSScriptAnalyzer PowerShell/PSScriptAnalyzer#712
SteveL-MSFT commentedon Aug 24, 2017
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)