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

Welcome Forums General PowerShell Q&A How to select multiple file paths, PS equiv of linux {}

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
4 years, 8 months ago.

  • Author
    Posts
  • #12859

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Whoo! .3 seconds!

    Thanks 🙂

The topic ‘How to select multiple file paths, PS equiv of linux {}’ is closed to new replies.