How to select multiple file paths, PS equiv of linux {}

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Jesse Petre Jesse Petre 3 years, 2 months ago.

  • Author
    Posts
  • #12859
    Profile photo of Jesse Petre
    Jesse Petre
    Participant

    I want to select some image files out of a directory. If I were on Linux I would type this:
    ls /docs/{*.tif,*.tiff,*.jpg,*.jpeg}
    How do I do this in PowerShell? I first tried Get-Item -Path C:\docs\*.tif,*.tiff,*.jpg,*.jpeg but it didn't work.
    The best I can come up with is this, but it seems sloppy to me.
    get-item -Path C:\docs\*.tif,C:\docs\*.jpg,C:\docs\*.tiff,C:\docs\*.jpeg
    Is there a better way to accomplish this?

  • #12860
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    You can pass multiple extensions to the -Include parameter, instead of putting the wildcards in to the Path parameter:

    Get-ChildItem -Path C:\docs\* -Include '*.tif', '*.tiff', '*.jpg', '*.jpeg'
    

    That trailing * on the Path does seem to be necessary; I didn't get any results until I added it. Not sure why.

  • #12861
    Profile photo of Jesse Petre
    Jesse Petre
    Participant

    Dave, thanks for the suggestion. I like that syntax better.
    I did notice it took 9.5s to complete on my system whereas using Get-Item took 6.5s

  • #12862
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    This will probably beat both of them for performance, if that's a factor in your choice. You need at least PowerShell 3.0 (.NET Framework 4.0) for the EnumerateFiles() method, though. In PowerShell 2.0 you'd be limited to using GetFiles(), which isn't as fast and takes up more memory.

    The tradeoff is that the code isn't as concise, though you could stick it into a function.

    $extensions = @{
        '.tif' = $true
        '.tiff' = $true
        '.jpg' = $true
        '.jpeg' = $true
    }
    
    $folder = Get-Item C:\docs
    
    foreach ($file in $folder.EnumerateFiles())
    {
        if ($extensions.ContainsKey($file.Extension))
        {
            $file
        }
    }
    
  • #12863
    Profile photo of Jesse Petre
    Jesse Petre
    Participant

    Whoo! .3 seconds!

    Thanks 🙂

You must be logged in to reply to this topic.