Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only file with given extension in directory

I have a string variable pointing to a directory. In this directory is a single file with the extension .xyz. How do I get the path to this file, without knowing the file name itself?

I have the following code so far:

$dir = "C:\Temp\MyDir"
$xyzFiles = @(Get-ChildItem "$dir\*.xyz")
$file = $xyzFiles[0]

Is this "the way to go" in PowerShell? Is there a better solution?

like image 645
D.R. Avatar asked Jul 17 '17 15:07

D.R.


People also ask

How do I search for all files with specific extensions?

For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.

How would you search a file directory by extension?

To find all files with a file extension, write out its path to find a command with the options and expression specifying the extension. In the below-given example, we will find all files with the “. txt” extension.


1 Answers

In powerShell version 5, you can also try this: Get-ChildItem $dir -Recurse -Include *.xyz

like image 186
Ben Q Avatar answered Oct 03 '22 23:10

Ben Q