Search code examples
arraysfilepowershellpowershell-2.0get-childitem

Most efficient way to check if file extension ends in this OR that?


I had this code which I was really happy with:

$jpgExtensionFiles = New-Object System.Collections.ArrayList

$AllDrives = Get-PSDrive
  foreach ($Drive in $AllDrives) {
      $Dirs = Get-ChildItem $Drive.Root -Recurse -ErrorAction SilentlyContinue
      $jpgExtensionFiles.Add(($Dirs | where {$_.extension -eq ".jpg"}))         
   }

But now, I want to do the same thing for an array called $bmpExtensionFiles. I can't figure out how to do the following:

  1. If the extension is .jpg, add to the first array
  2. If the extension is .bmp, add to the second array

... all in one loop, for efficiency's sake. I know I can just add $bmpExtensionFiles.Add(($Dirs | where {$_.extension -eq ".bmp"})), but is there a more efficient way? I would need this compatible with PowerShell v2.


Solution

  • You could use a switch statement, then if you want to add further types later it's easy to expand:

    ForEach ($Dir in $Dirs)
    {
        Switch ($Dir.Extension)
        {
            ".jpg" {$jpgExtensionFiles.Add($Dir)}
            ".bmp" {$bmpExtensionFiles.Add($Dir)}
        }
    }