Get only file with given extension in directory

Viewed 17680

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?

7 Answers

Simplest solution:

Get-ChildItem $dir -File '*.xyz'

This should work:

Get-ChildItem $dir -File | Where-Object { $_.Extension -eq ".xyz" }
Related