Search code examples
windowspowershellps

Get-ChildItem with wild chars in path without "Where"


I want to use wild characters in path passed to Get-ChildItem. So in example I want to use C:\root\*\container as a path parameter. But this searches only in 1 level below. If I would write C:\root\*\*\container then it would search 2 levels below only.

I try to do something like Get-ChildItem -Path "C:\root\*\container\vc$number" "*test*.exe" -Recurse and copy results into certain directory. If I search recursively in C:\root I find too many files. If I use path given in an example then I search only 1 level below, not recursively in all directories (that can be even 5 levels deep). I know I can use

Get-ChildItem -Path "C:\root\" "*test*.exe" -Recurse | Where { %_.FullName -like "container\vc$number" }

but I was wondering if I can skip using Whereand use wild chars in path. Reason for that is I read paths from external file and some paths contain wild chars (as example above) and some don't. So I hope I don't have to write function that processes path and uses Get-ChildItem with / without Where

So in example I have

C:\root\container\*test*.exe, C:\root\a\container\*test*.exe, C:\root\b\container\*test*.exe, C:\root\c\x\y\container\*test*.exe, C:\root\c\x\y\z\g\container\*test*.exe

and so on. And with C:\root\*\container I want to find all of them


Solution

  • Get-Childitem has a parameter Filter which you can use to filter the results you want. In your case (as i understood) you want to get files in all the directories named "container".

    First you have to get the path to these directories, then get the files inside as follows:

    Get-ChildItem "C:\root" -filter "*container*" -recurse | Get-ChildItem
    

    Output

    C:\root\a\container\new.exe
    C:\root\b\container\sample.exe
    C:\root\c\x\y\z\g\container\anything.exe
    

    I used .Fullname at the end to get them displayed as above