Search code examples
windowspowershellglob

Powershell glob pattern matching


I am looking through C:\ProgramFiles for a jar file named log4j-core-x.y.z.jar. I am trying to match on the last digit z, which can be both a one or two digit number (0-99). I can't seem to get the right glob pattern to accomplish this.

Code:

PS C:\Users\Administrator> Get-ChildItem -Path 'C:\Program Files\' -Filter log4j-core-*.*.[1-9][0-9].jar -Recurse -ErrorAction SilentlyContinue -Force | %{$_.FullName}

This yields no results, but when I just do all wildcards like, -Filter log4j-core-*.*.*.jar, I get:

C:\Program Files\apache-log4j-2.16.0-bin\apache-log4j-2.16.0-bin\log4j-core-2.16.0-javadoc.jar
C:\Program Files\apache-log4j-2.16.0-bin\apache-log4j-2.16.0-bin\log4j-core-2.16.0-sources.jar
C:\Program Files\apache-log4j-2.16.0-bin\apache-log4j-2.16.0-bin\log4j-core-2.16.0-tests.jar
C:\Program Files\apache-log4j-2.16.0-bin\apache-log4j-2.16.0-bin\log4j-core-2.16.0.jar

The only thing I care about getting is C:\Program Files\apache-log4j-2.16.0-bin\apache-log4j-2.16.0-bin\log4j-core-2.16.0.jar, log4j-core-2.16.0.jar


Solution

  • -Filter doesn't support filtering with regex or Character ranges such as [A-Z] or [0-9]. Thanks mklement0 for pointing it out.

    From the parameter description of Get-ChildItem official documentation:

    The filter string is passed to the .NET API to enumerate files. The API only supports * and ? wildcards.

    Try with this:

    $getChildItemSplat = @{
        Path        = 'C:\Program Files\'
        Filter      = 'log4j-core-*.*.??.jar'
        Recurse     = $true
        ErrorAction = 'SilentlyContinue'
        Force       = $true
    }
    
    Get-ChildItem @getChildItemSplat |
        # Ends with a . followed by 1 or 2 digits and the .jar extension
        Where-Object Name -Match '\.\d{1,2}\.jar$'