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
I can deal with null, but how do I just select the "first" file?
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.
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.
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.
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:
$null
of there wasn't any object to begin withThere 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With