Skip to content

switch -File unexpectedly and invariably interprets the path as a wildcard expression #8988

Closed

Description

Related: #4726

Steps to reproduce

New-Item 'foo[0].txt'
switch -File 'foo[0].txt' { default { 'hi' } }

Expected behavior

No output (the file is empty, there's nothing for switch -File to iterate over).

Actual behavior

The following error occurs:

No files matching 'foo[0].txt' were found.

That is, filename foo[0].txt was interpreted as a wildcard pattern, not a literal name.

With the current behavior, the workaround is to `-escape the [ and ] chars.

Note that even successfully resolving the wildcard expression ultimately fails if it resolves to multiple filenames, so the utility of interpretation-as-wildcard is questionable.

Environment data

PowerShell Core v6.2.0-preview.4 on macOS 10.14.2
PowerShell Core v6.2.0-preview.4 on Ubuntu 18.04.1 LTS
PowerShell Core v6.2.0-preview.4 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)
Windows PowerShell v5.1.17134.407 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)

Activity

  1. added
    Issue-Question
    on Feb 26, 2019
  2. changed the title [-]switch -File unexpectedly and invariably interprets the path as a wildcard expression[/-] [+]`switch -File` unexpectedly and invariably interprets the path as a wildcard expression[/+] on Feb 26, 2019
  3. iSazonov commented on Feb 26, 2019

    @iSazonov
    Collaborator

    Do you mean that we should interpret the path as Literal? It is not a breaking change and I like it.

    Rob Holt (@rjmholt) It could be good issue for hackathon if you still continue.

  4. added
    Issue-Enhancement
    WG-Engine
    Hacktoberfest
    and removed
    Issue-Question
    on Feb 26, 2019
  5. mklement0 commented on Feb 26, 2019

    @mklement0
    ContributorAuthor

    Ilya (@iSazonov): Yes, as in the case of #4726 I think the path should always have been interpreted as a literal path.

    Do note, however, that it is technically a breaking change, because someone could rely on code such as the following:

    # Note: Only works if exactly ONE *.txt file exists in the current dir.
    switch -file *.txt { 'hi' { 'there' } }

    That said, I think it's a Bucket 3: Unlikely Grey Area change.

  6. added
    Breaking-Change
    on Feb 26, 2019
  7. iSazonov commented on Feb 26, 2019

    @iSazonov
    Collaborator

    Steve Lee (@SteveL-MSFT) Could PowerShell Committee approve the breaking change?

  8. IISResetMe commented on Feb 28, 2019

    @IISResetMe
    Collaborator

    Wouldn't it be better to just clarify this in the documentation? It's easily solved:

    $file = [WildcardPattern]::Escape('foo[0].txt')
    switch -file $file { 'abc' { 'something something' } }
  9. vexx32 commented on Feb 28, 2019

    @vexx32
    Collaborator

    I mean, given the fact that having a wildcard that resolves to multiple files fails with no reason I think that it would make more sense to be a literal path.

    The alternative would be to fix the wildcard interpretation by a) allowing it to actually work with wildcards that resolve to multiple files, and b) add a -LiteralFile switch instead to allow ease of use with literal paths.

    Both should probably accept an array of values, too.

  10. iSazonov commented on Feb 28, 2019

    @iSazonov
    Collaborator

    I'd consider the Issue as UX issue. Any complications worsen UX. So allowing wildcards implicitly convert switch to cycle that is likely to worsen UX.

  11. mklement0 commented on Feb 28, 2019

    @mklement0
    ContributorAuthor

    If we stick with the current single-input-file-only behavior:

    • The always-as-wildcard interpretation is so useless and unexpected (as it is in the invocation scenarios in Some scripts / files with wildcard metacharacter [ in the file name or path cannot be invoked or redirected to #4726) that the only reason to stick with it would be the fear of breaking existing code.

    • Since I think it's pretty unlikely someone relied on the old behavior (why would you use a wildcard that you know must resolve to a single file and not just target that single file directly? if you don't know, use Get-Item / Convert-Path / Resolve-Path), the behavior should be fixed.


    Allowing multiple input files is intriguing, but I think it would requires additional functionality to be useful:

    • Access to information about the file currently being processed.

    • Possibly also allow actions to be taken before and after a given file has been processed, along the lines of GNU awk's BEGINFILE / ENDFILE patterns.

    While switch -File currently languishes in obscurity, perhaps adding such functionality could make it a more widely used tool; it certainly provides great performance benefits.

    Even then it's possible to stay away from wildcards, however, so as to avoid the whole -Path / -LiteralPath (-File, -LiteralFile) mess; with array support, you could then write:

    switch -File (Get-Item *.txt) { ...
  12. iSazonov commented on Feb 28, 2019

    @iSazonov
    Collaborator

    Looks like duplication of Select-String.

  13. 23 remaining items

  14. mklement0 commented on Apr 15, 2019

    @mklement0
    ContributorAuthor

    Thanks for the examples, Patrick Meinecke (@SeeminglyScience).

    While there is an inherent tension between designing for interactive convenience and readability / long-term maintainability, PowerShell by and large does a great job of accommodating both - but there's plenty of room for improvement.

    Syntax is designed around accommodating interactive use. Member expressions cannot have the . on a new line. Curly brackets cannot be on a new line during command parsing

    True, but the curly braces restriction doesn't apply in expression mode, and in expression mode you can at least end the line with . in order to continue on the next line.

    Module autoloading.

    This problem strikes me as solvable: with side-by-side module loading using fully qualified module names and scoped module imports.

    Aliases

    A current problem for sure, but we could take a page out of Bash's book, where alias expansion is turned off in scripts by default; see #2000 (comment)

    My linked comment also proposes an opt-in for disallowing elastic syntax in scripts (such as using -Expand for -ExpandProperty).

    On the flip side, #4730 proposes making elastic syntax even more elastic by allowing you to prefix-abbreviate operator names (e.g., 'foo' -m 'o' for 'foo' -match 'o').

    There are lots of issues where state (variables, commands, imported modules, etc) is leaked into a script in unexpected and difficult to troubleshoot ways.

    Indeed, PowerShell currently has a problem with global state affecting code, taking the global effect of Set-Location and the dynamic scoping of Set-StrictMode as examples.

    Even the dynamic scoping of variables (descendent scopes seeing a caller's variables by default) is worth reconsidering.

    Again, these problems are solvable.

    As an aside: Bash doesn't have the working-dir. problem, for instance, because its scripts execute in a child process; for the same reason, there's no ability to modify the global scope.

  15. SeeminglyScience commented on Apr 15, 2019

    @SeeminglyScience
    Contributor

    True, but the curly braces restriction doesn't apply in expression mode, and in expression mode you can at least end the line with . in order to continue on the next line.

    Yeah it's limited in scope for sure, just something that bothers me personally a lot.

    Note: I'm not advocating for it to be changed, I understand why it is the way it is and I don't see a better solution. It's still the first example I can think of though 🙂

    This problem strikes me as solvable: with side-by-side module loading using fully qualified module names and scoped module imports.

    I would be more inclined to call fully qualifying commands is a workaround than a fix. It severely hurts readability and forces you to splat just about every command if you also want to keep a reasonable line length.

    I'm not clear on what you mean by scoped module imports.

    A current problem for sure, but we could take a page out of Bash's book, where alias expansion is turned off in scripts by default; see #2000 (comment)

    I would absolutely love to see an opt-in AST-level (similar to using) setting for that. I think making it default would cause enough issues to hurt adoption significantly.

    On the flip side, #4730 proposes making elastic syntax even more elastic by allowing you to prefix-abbreviate operator names (e.g., 'foo' -m 'o' for 'foo' -match 'o').

    I've always wanted that for interactive use 😁 I mess that up going back and forth between ? prop -m value and ? {$_.prop.otherprop -m 'value'} at least once a day. Unfortunately I also agree that it probably shouldn't happen to allow for new operators. Though I dream of a hacky way I could enable it in my profile 🙂

    Even the dynamic scoping of variables (descendent scopes seeing a caller's variables by default) is worth reconsidering.

    Again I'd love to see an AST-level modifier for this. Default seems a bit too far on the drastic side, I think that ship has sailed.

    Also just to clarify, I didn't necessarily give those examples as things that need to be fixed. They all have work arounds (though some of them should certainly have better work arounds) They're just examples of the scripting experience taking a hit for the good of the interactive experience. Whether or not they should be fixed is certainly debatable, but they are still decisions that were made at least partially to cater to interactivity.

  16. mklement0 commented on Apr 15, 2019

    @mklement0
    ContributorAuthor

    As for opt-in vs. changing defaults:

    Understood that opt-ins are the best we can do if backward compatibility is a must.
    But at some point we're back to #6745 and the hope that there may be a version that can shed historical baggage and doesn't require explicit opt-in to what should be the default.

    I would be more inclined to call fully qualifying commands is a workaround than a fix.

    If you want robust dependency management, you need to be explicit about version number [ranges].
    Fully agreed that the current method for specifying FQMN (fully-qualified module names) is unwieldy, but can we can take a page out of npm's book, with identifiers such as PSReadline@1.2 - and generally establishing semver (semantic versioning) in the PowerShell world sounds like a worthwhile goal as well.

    I'm not clear on what you mean by scoped module imports.

    Currently, module imports take effect scope-domain-wide by default (by scope domain I mean the scope stacks for non-module code vs. each module's).

    Just like we're discussing variables and strict mode as perhaps better being lexically scoped, so could modules.

    You can already restrict Import-Module to the current scope with -Scope Local, but (a) it's an explicit opt-in and (b) its descendants again see the imports too, and - perhaps most importantly - using module is implicitly and invariably scope-domain-wide.

    They're just examples of the scripting experience taking a hit for the good of the interactive experience.

    Among all the things discussed, the only one that strikes me as inherently necessary - due to PowerShell having to be both a shell and a full-fledged scripting language - is the one related to argument mode vs. expression mode (curly braces, periods); as an aside: Kirk Munro (@KirkMunro)'s PR for allowing | to be placed on the next line - #8938 - will bring some relief there.

    All others need not be compromises, and should be fixed:

    • as opt-ins, if backward compatibility is paramount

    • by changing the default behavior, in a version allowed to break compatibility

  17. SeeminglyScience commented on Apr 16, 2019

    @SeeminglyScience
    Contributor

    Understood that opt-ins are the best we can do if backward compatibility is a must.
    But at some point we're back to #6745 and the hope that there may be a version that can shed historical baggage and doesn't require explicit opt-in to what should be the default.

    I'm not suggesting it be opt-in purely for compatibility. I don't agree that we should make scripts act all that differently by default. I'd love to see some opt-in options for making a script or module a lot more strict, but having code that runs (more or less) the same in a script as it does interactively is incredibly valuable. That keeps the learning curve very approachable and makes experimentation and prototypes a breeze. I'd love to see the opt-in settings for an easier way to get a more stable experience in large scale deployments/unknown environments, I do worry about the effect such a default would have outside of that scenario.

    If you want robust dependency management, you need to be explicit about version number [ranges].
    Fully agreed that the current method for specifying FQMN (fully-qualified module names) is unwieldy, but can we can take a page out of npm's book, with identifiers such as PSReadline@1.2 - and generally establishing semver (semantic versioning) in the PowerShell world sounds like a worthwhile goal as well.

    Yeah for sure, but my point is that it shouldn't need to be declared on every instance of every command invocation.

    We need a way to say I want command discovery to prioritize:

    • Module x
    • With version y
    • For this scope/module

    So when you call Get-Item It doesn't import a version from C:\BadVendor\MyHackyCommandOverrides.psd1 with no Path parameter. Right now you can do Microsoft.PowerShell.Management\Get-Item but a script full of that is very difficult to read.

    Currently, module imports take effect scope-domain-wide by default (by scope domain I mean the scope stacks for non-module code vs. each module's).

    I know you probably already know this, but for anyone else following: PowerShell refers to that as a SessionState. There's one for each module and one that is global (referred to by the engine as the top level session state)

    I'm not really sure the benefit of changing it to default to scope, but I don't have very strong opinions on it.

    Among all the things discussed, the only one that strikes me as inherently necessary - due to PowerShell having to be both a shell and a full-fledged scripting language

    I didn't mean to imply there was no other choice, or even that interactivity was the sole reason behind those decisions. I do believe though, that they were made at least in part if not mostly because of how they would impact interactivity. I don't really know if I would refer to these decisions as things to be solved, but an opt-in way to overcome the drawbacks of them would be awesome.

  18. mklement0 commented on Apr 16, 2019

    @mklement0
    ContributorAuthor

    but having code that runs (more or less) the same in a script as it does interactively is incredibly valuable.

    Fully agreed, but there's a simpler solution: have distinct filename extensions:

    • one for "loose" code, just like on the command line.
    • one for strict code, where the extension alone turns on - and enforces - all behaviors needed for robust development

    I know you probably already know this, but for anyone else following: PowerShell refers to that as a SessionState

    I do know, thanks to your excellent blog post exploring the subject: https://seeminglyscience.github.io/powershell/2017/09/30/invocation-operators-states-and-scopes

    However, I think this term invites everlasting confusion, and given that it isn't yet widely known - fortunately, in this case - I was hoping to get a more descriptive name established, and my suggestion is scope domain: the default scope domain for non-module code, and one module scope domain for each loaded module - writing up a proposal in the docs repo has been on my to-do list for some time.

    I'm not really sure the benefit of changing it to default to scope, but I don't have very strong opinions on it.

    It's the same benefit as with all other instances of lexical scoping: what you do in the privacy of your own scope (if you will) doesn't affect others: my importing a module shouldn't magically make commands appear in your scope - unless that is the explicit intent.

    I do believe though, that they were made at least in part if not mostly because of how they would impact interactivity

    The question is ultimately moot: It sounds like we agree that there are problems with the existing behavior and that we should think about ways to make things better (without compromising the interactive experience).

  19. SeeminglyScience commented on Apr 16, 2019

    @SeeminglyScience
    Contributor

    Fully agreed, but there's a simpler solution: have distinct filename extensions:

    one for "loose" code, just like on the command line.
    one for strict code, where the extension alone turns on - and enforces - all behaviors needed for robust development

    Love it ❤️

    I do know, thanks to your excellent blog post exploring the subject:

    😁

    However, I think this term invites everlasting confusion, and given that it isn't yet widely known - fortunately, in this case - I was hoping to get a more descriptive name established, and my suggestion is scope domain: the default scope domain for non-module code, and one module scope domain for each loaded module - writing up a proposal in the docs repo has been on my to-do list for some time.

    The word domain makes me think of something as Runspace level. It took me a few reads to get what you meant. To each their own on this one, I generally stick to referring to things as the engine does, but I can definitely see your point.

  20. mklement0 commented on May 9, 2019

    @mklement0
    ContributorAuthor

    Glad to hear it, Patrick Meinecke (@SeeminglyScience).

    Regarding the terminology question: I've finally created a docs issue, and I invite you to weigh in there (I've already quoted your concern re scope domain there): MicrosoftDocs/PowerShell-Docs#4288

  21. iSazonov commented on May 10, 2019

    @iSazonov
    Collaborator

    Interesting, why do we consider only files? We could generalize to support any provider with -Path/-LiteralPath.

  22. vexx32 commented on May 10, 2019

    @vexx32
    Collaborator

    We can use the same restriction that ${C:\test.txt} has - the provider must support Get-Content functionality.

    Sounds good to me. However, then we have the semantic issue where this really ought to be named switch -Path file.txt / switch -LiteralPath file[].txt

    Can we alias these in some fashion?

  23. 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.

  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. added
    Resolution-No Activity
    on Nov 16, 2023
  26. 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.

  27. added
    In-PR
    on Mar 30, 2025
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-ChangeHacktoberfestIn-PRIssue-EnhancementResolution-No ActivityUp-for-GrabsWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions