Skip to content

Some scripts / files with wildcard metacharacter [ in the file name or path cannot be invoked or redirected to #4726

Closed

Description

Edited for the current status as of PowerShell Core 7.3.0-preview.4

Note:

  • Originally, this issue was also about the inability to execute files whose literal names happen to be syntactically invalid wildcard patterns.

  • This execution aspect was partially fixed in Make command searcher not use wildcard search for execution #9202 (but wasn't back-ported to the currently stable version, v6.2.3)

    • Invocation by wildcard pattern still works as a fallback, but paths with [ and ] that exist literally now take precedence.
    • Therefore, if no literal match is present, you may still end up invoking an unrelated file by accident, which is problematic (e.g., if a.ps1 is present in the current dir. and .\[ab].ps1 is invoked, with no file literally named [ab].ps1 present, .\a.ps1 is executed instead.)

Seemingly, all external-executable invocation methods ( ., &, Start-Process, powershell -File) as well as redirections > / >> mistakenly interpret script / file paths as wildcard patterns, and if a path that contains [ happens not contain a syntactically valid range expression, invocation and redirection break (in Windows PowerShell, no longer in PowerShell Core, except with Start-Process) or can end up accidentally targeting an unrelated executable.

  • In other words: The problem sometimes occurs, unless each instance of [ happens to be part of a valid range expression; e.g., a[b] (valid) vs. a[b (invalid); curiously, however, the equally invalid b[b does not.

  • But even with a syntactically valid range expression - and some invalid ones - the behavior is unexpected:

  • Attempting to invoke (open) such a file fails quietly, even with escaping (run New-Item file[1].txt first):

    • ./file[1].txt ... quiet no-op
    • ./file`[1`].txt ... quiet no-op
    • If you created a .ps1 file named, say, file[1].ps1 ('"hi"' | Set-Content -LiteralPath file[1].ps1):
      • Invocation with an explicit path unexpectedly only works if .ps1 is also specified.
      • Invocation via $env:PATH doesn't work at all - neither with or without .ps1

Fundamentally, external-executable / redirection output paths should be treated as literals in these situations.
See this comment for a discussion and an overview of related issues.

Original tests below.

Steps to reproduce

Run the following Pester tests.

Describe "Redirection with and invocation of literal file paths that are invalid as wildcard patterns" {

  BeforeAll {
    Push-Location testdrive:\
    $f1 = './t[1.ps1'
    $f2 = './t[1.txt'
    New-Item -Type File $f1 -Value "'hi'"
  }

 # Passes now, due to fix in #9202
  It "Script file can be dot-sourced." {
    . $f1 | Should -Be 'hi'
  }

 # Passes now, due to fix in #9202
  It "Script file can be called." {
    & $f1 | Should -Be 'hi'
  }

 # Passes now, due to fix in #9202
  It "Script file can be called via CLI with -File" {
    pwsh -noprofile -file $f1 | Should -Be 'hi'
  }

  It "Redirection works with new file (>)" {
    & { 'hi' > $f2; Get-Content -LiteralPath $f2 } | Should -Be 'hi'
  }

  It "Redirection works with existing file (>)" {
    New-Item -Force -Type File $f2
    & { 'hi' > $f2; Get-Content -LiteralPath $f2 } | Should -Be 'hi'
  }

  It "File path is passed correctly to external programs" {
    if ($IsWindows) {
      cmd /c type ($f1 -replace '/', '\') | Should -Be "'hi'"
    } else {
      /bin/cat $f1 | Should -Be "'hi'"
    }
  }

  AfterAll {
    Pop-Location
  }
}

Expected behavior

All tests should pass.

Actual behavior

The > tests fail on all platforms.

In v6.2.3, the invocation tests fail too.

Environment data

PowerShell Core 7.0.0-preview.5

Originally reported for PowerShell Core v6.0.0-beta.7.

Activity

  1. changed the title [-]Scripts with wildcard metacharacters [ and ] in the file name or path cannot be invoked or redirected to[/-] [+]Some scripts / files with wildcard metacharacter [ in the file name or path cannot be invoked or redirected to[/+] on Sep 1, 2017
  2. iSazonov commented on Sep 4, 2017

    @iSazonov
    Collaborator

    It seems we should escape (try tab completion):

    . './t`[`].ps1'
    
  3. mklement0 commented on Sep 4, 2017

    @mklement0
    ContributorAuthor

    No, I think there is no reason to attempt wildcard pattern matching at all in all these scenarios - the paths should be taken as literals, which obviates the need for escaping.

  4. iSazonov commented on Sep 4, 2017

    @iSazonov
    Collaborator
  5. mklement0 commented on Sep 4, 2017

    @mklement0
    ContributorAuthor

    When tab-completing for parameters that support wildcards, the escaping you mention makes sense:

    # -Path implied, which supports wildcards -> escaping
    Get-Item './t`[`].ps1'  # The result of typing Get-Item ./t<tab> *on Unix*
    
    # -LiteralPath specified, which does NOT support wildcards -> NO escaping
    Get-Item -LiteralPath ./t[].ps1  # The result of typing Get-Item -LiteralPath ./t<tab>

    Since there is no good reason to treat the file path in scenarios such as . <file-path> as a wildcard pattern:

    • tab completion should work the same way it does with Get-Item -LiteralPath - treat it as a literal.

    • and execution of such a path should obviously succeed.

  6. iSazonov commented on Sep 4, 2017

    @iSazonov
    Collaborator

    Here can be a root of the bug.

  7. added
    WG-Engine
    Issue-Bug
    on Sep 4, 2017
  8. daxian-dbw commented on Sep 16, 2017

    @daxian-dbw
    Member

    Michael Klement (@mklement0) The file redirection is broken for this scenario, but the invocations seem working fine on beta.7:

    PS:4> '"Hi!"' | Set-Content -literalpath './t[].ps1'
    [F:\tmp]
    PS:5> ./t[].ps1
    Hi!
    [F:\tmp]
    PS:6> . './t[].ps1'
    Hi!
    [F:\tmp]
    PS:7> & './t[].ps1'
    Hi!
    [F:\tmp]
    PS:8> E:\pscore\powershell.exe -noprofile -file './t[].ps1'
    Hi!
    [F:\tmp]
    PS:9>
    

    The $PSVersion:

    PS:9> $PSVersionTable
    
    Name                           Value
    ----                           -----
    PSVersion                      6.0.0-beta
    PSEdition                      Core
    GitCommitId                    v6.0.0-beta.7
    OS                             Microsoft Windows 10.0.15063
    Platform                       Win32NT
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    PSRemotingProtocolVersion      2.3
    SerializationVersion           1.1.0.1
    WSManStackVersion              3.0
    

    Am I missing something?

  9. mklement0 commented on Sep 18, 2017

    @mklement0
    ContributorAuthor

    Dongbo Wang (@daxian-dbw):

    Sorry, I didn't realize that the behavior varies with similar filenames present in the same directory.

    I've updated the original post with scenarios that should fail predictably with initially empty directories, on both Windows and Unix platforms.

    The key is to use something like t[.ps1 - something truly invalid if interpreted as a wildcard pattern.

  10. daxian-dbw commented on Sep 18, 2017

    @daxian-dbw
    Member

    Michael Klement (@mklement0) Thanks for the clarification!

  11. TravisEz13 commented on Mar 22, 2019

    @TravisEz13
    Member

    Michael Klement (@mklement0) This issue is about redirection. Which occurs at execution time, but it is not about what you execute. I think this would drop it out of the Defense in Depth category and into a functional issue. If you believe this is a security issue, Please report this issue to secure@microsoft.com per the contribution guidelines and not via GitHub. If they determine that the issue, can be disclosed publicly, feel free to post security issues here.

  12. mklement0 commented on Mar 22, 2019

    @mklement0
    ContributorAuthor

    Travis Plunk (@TravisEz13), quoting from the OP (emphasis added):

    Seemingly, all external-executable invocation methods ( ., &, Start-Process, powershell -File) as well as redirections > / >> mistakenly interpret script / file paths as wildcard patterns,

    Similarly, the repro steps show execution commands.

    So, as stated in #9202, the latter therefore addresses part of this issue, correct?

    As for the other part of this issue, redirection: no, I don't think it is security-critical.

  13. mklement0 commented on Mar 22, 2019

    @mklement0
    ContributorAuthor

    (The execution issue is framed differently here, because my angle was the inability to execute, but my understanding is that #9202 will fix that too.)

  14. TravisEz13 commented on Mar 22, 2019

    @TravisEz13
    Member

    Yes... sorry... I was reading only the parts, not address by #9202 . I'm in a bit of a rush to get that PR done and some of the suggested changes have broken the PR. I'm trying to track back which change broke the PR.

  15. 4 remaining items

  16. mklement0 commented on Mar 22, 2019

    @mklement0
    ContributorAuthor

    I appreciate the pointers, Travis Plunk (@TravisEz13).

  17. msftrncs commented on Jul 24, 2019

    @msftrncs
    Contributor

    Attempting to escape the wildcard characters from a redirection target argument is still broken. I ran in to this issue testing file path completion scenario's.

  18. arberg commented on Oct 25, 2019

    @arberg

    I suspect this bug I found is this issue, but since I'm not sure I think its valuable if I add the details:

    Somehow create the file: c:\temp\ivydata-[2.4,).properties
    piping to the file in powershell does not work, it gives the same error.

    > pwsh -version
    PowerShell 6.2.3
    
    C:\temp> Test-Path -PathType Leaf "c:\temp\ivydata-[2.4,).properties"
    Test-Path : The specified wildcard character pattern is not valid: ivydata-[2.4,).properties
    At line:1 char:1
    + Test-Path -PathType Leaf "c:\temp\ivydata-[2.4,).properties"
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Test-Path], WildcardPatternException
    + FullyQualifiedErrorId : RuntimeException,Microsoft.PowerShell.Commands.TestPathCommand
    
    C:\temp> dir \temp\*.properties | %{test-path $_}
    Test-Path : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: ivydata-[2.4,).properties
    At line:1 char:28
    + dir \temp\*.properties | %{test-path $_}
    +                            ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Test-Path], ParameterBindingException
    + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.TestPathCommand
    
    

    ps: I found the file under c:\users<myname>.ivy2

  19. mklement0 commented on Oct 25, 2019

    @mklement0
    ContributorAuthor

    Thanks, arberg, but the behavior you're seeing is by design, because positionally passing a path to Test-Path implicitly binds to the -Path parameter, which by design interprets its argument as a wildcard expression. If you use Test-Path -LiteralPath "c:\temp\ivydata-[2.4,).properties", the problem goes away.

    By contrast, the issue at hand is that when you use > / >> you (a) don't get a choice about how the path is interpreted and (b) the implied behavior should be the same as with -LiteralPath, i.e. interpretation as a literal path.

    In the past, the same problem existed for invoking files, but that has been fixed in #9202 (though not back-ported to 6.2.3).

    I've updated the OP with the current bug status and Pester tests.

  20. msftrncs commented on Nov 7, 2019

    @msftrncs
    Contributor

    Here is the code for the redirection:

    CommandProcessorBase commandProcessor = context.CreateCommand("out-file", false);
    Diagnostics.Assert(commandProcessor != null, "CreateCommand returned null");
    // Previously, we mandated Unicode encoding here
    // Now, We can take what ever has been set if PSDefaultParameterValues
    // Unicode is still the default, but now may be overridden
    var cpi = CommandParameterInternal.CreateParameterWithArgument(
    /*parameterAst*/null, "Filepath", "-Filepath:",
    /*argumentAst*/null, File,
    false);
    commandProcessor.AddParameter(cpi);
    if (this.Appending)
    {
    cpi = CommandParameterInternal.CreateParameterWithArgument(
    /*parameterAst*/null, "Append", "-Append:",
    /*argumentAst*/null, true,
    false);
    commandProcessor.AddParameter(cpi);
    }

    Of course, changing this, makes it a breaking change.

  21. msftrncs commented on Nov 7, 2019

    @msftrncs
    Contributor

    Also, it really seems like its Out-File that is broken. Its not processing wildcard paths correctly, when they have been escaped. Doesn't seem to be something specific to Out-File, as it calls the LocationGlobber to handle wildcards ...

  22. mklement0 commented on Nov 7, 2019

    @mklement0
    ContributorAuthor

    Thanks for the pointer, Carl Morris (@msftrncs):

    As for broken escaping in wildcards - see #7999

    As for making > / >> bind to Out-File's -LiteralPath parameter instead being a breaking change:

    Technically, yes, but the current behavior is unexpected, always fraught and mostly useless:

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

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

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

    In-PRIssue-BugResolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions