Search code examples
powershellstring-formatting

Filenames matching regex but in folder with wildcard


This is a follow up question of: PowerShell concatenate output of Get-ChildItem

This code works fine:

Get-ChildItem -Path "D:\Wim\TM1\TI processes" -Filter "*.vue" -Recurse -File |
    Where-Object { $_.BaseName -match '^[0-9]+$' } |
    ForEach-Object { ($_.FullName -split '\\')[-2,-1] -join '\' } |
    Out-File D:\wim.txt

But I would need to restrict the search folder to only certain folders, basically, this filter: D:\Wim\TM1\TI processes\\*}vues (so all subfolders ending in }vues).

If I add that wildcard condition I get no result. Without the restriction, I get the correct result. Is this possible please?

without filter

with filter

The idea is to get rid of the 3rd line in the first output (which was a copy/paste by me) and also to minimize the number of folders to look at.


Solution

  • You can nest two Get-ChildItem calls:

    • An outer Get-ChildItem -Directory -Recurse call to filter directories of interest first,

    • an inner Get-ChildItem -File call that, for each directory found, examines and processes the files of interest.

    Get-ChildItem -Path "D:\Wim\TM1\TI processes" -Filter "*}vues" -Recurse -Directory |
      ForEach-Object {
        Get-ChildItem -LiteralPath $_.FullName -Filter "*.vue" -File | 
          Where-Object { $_.BaseName -match '^[0-9]+$' } | 
            ForEach-Object { ($_.FullName -split '\\')[-2,-1] -join '\' }                 
      } | Out-File D:\wim.txt
    

    Note: The assumption is that all *.vue files of interest are located directly in each *}vues folder.


    As for what you tried:

    Given that you're limiting items being enumerated to files (-File), your directory-name wildcard pattern *}vues never gets to match any directory names and, in the absence of files matching that pattern, returns nothing.

    Generally, with -Recurse it is conceptually cleaner not to append the wildcard pattern directly to the -Path argument, so as to better signal that the pattern will be matched in every directory in the subtree.

    In your case you would have noticed your attempt to filter doubly, given that you're also using the -Filter parameter.