Find the first file that matches a pattern using PowerShell

Powershell

Powershell Problem Overview


I would like to select any one ".xls" file in a directory. The problem is the dir command can return different types.

gci *.xls

will return

  • object[] if there is more than one file
  • FileInfo if there is exactly one file
  • null if there are no files

I can deal with null, but how do I just select the "first" file?

Powershell Solutions


Solution 1 - Powershell

You can force PowerShell into returning an array, even when only one item is present by wrapping a statement into @(...):

@(gci *.xls)[0]

will work for each of your three cases:

  • it returns the first object of a collection of files
  • it returns the only object if there is only one
  • it returns $null of there wasn't any object to begin with

There is also the -First parameter to Select-Object:

Get-ChildItem -Filter *.xls | Select-Object -First 1
gci -fi *.xls | select -f 1

which works pretty much identical to the above, except that the list of files doesn't need to be enumerated completely by Get-ChildItem, as the pipeline is aborted after the first item. This can make a difference when there are many files matching the filter.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge MauerView Question on Stackoverflow
Solution 1 - PowershellJoeyView Answer on Stackoverflow