Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first file that matches a pattern using PowerShell

Tags:

powershell

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?

like image 537
George Mauer Avatar asked Sep 30 '09 19:09

George Mauer


People also ask

How do I find a specific file in PowerShell?

Get-ChildItem cmdlet in PowerShell is used to get items in one or more specified locations. Using Get-ChildItem, you can find files. You can easily find files by name, and location, search file for string, or find file locations using a match pattern.

How do I get strings in PowerShell?

You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

How do I get a list of files in a directory in PowerShell?

If you want to list files and directories of a specific directory, utilize the “-Path” parameter in the “Get-ChildItem” command. This option will help PowerShell list all the child items of the specified directory. The “-Path” parameter is also utilized to set the paths of one or more locations of files.


1 Answers

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.

like image 118
Joey Avatar answered Oct 05 '22 21:10

Joey