使用PowerShell查找与模式匹配的第一个文件

时间:2023-01-30 13:57:33

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

我想在目录中选择任何一个“.xls”文件。问题是dir命令可以返回不同的类型。

gci *.xls

will return

将返回

  • object[] if there is more than one file
  • object []如果有多个文件
  • FileInfo if there is exactly one file
  • 如果只有一个文件,则为FileInfo
  • null if there are no files
  • 如果没有文件,则返回null

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

我可以处理null,但是如何选择“第一个”文件呢?

1 个解决方案

#1


86  

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

您可以通过将语句包装到@(...)中来强制PowerShell返回一个数组,即使只有一个项目存在:

@(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
  • 它返回$ null,没有任何对象开始

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

Select-Object还有-First参数:

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.

与上面的工作方式完全相同,除了文件列表不需要由Get-ChildItem完全枚举,因为管道在第一个项目之后被中止。当有许多文件与过滤器匹配时,这会有所不同。

#1


86  

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

您可以通过将语句包装到@(...)中来强制PowerShell返回一个数组,即使只有一个项目存在:

@(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
  • 它返回$ null,没有任何对象开始

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

Select-Object还有-First参数:

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.

与上面的工作方式完全相同,除了文件列表不需要由Get-ChildItem完全枚举,因为管道在第一个项目之后被中止。当有许多文件与过滤器匹配时,这会有所不同。