I wanted to write a small script that searched for an exact file name, not a string within a file name.
For instance if I search for ‘hosts’ using Explorer, I get multiple results by default. With the script I want ONLY the name I specify. I’m assuming that it’s possible?
I had only really started the script and it’s only for my personal use so it’s not important, it’s just bugging me. I have several drives so I started with 2 inputs, one to query drive letter and another to specify file name. I can search by extension, file size etc but can’t seem to pin the search down to an exact name.
Any help would be appreciated!
EDIT : Thanks to all responses. Just to update. I added one of the answers to my tiny script and it works well. All three responses worked but I could only use one ultimately, no offence to the other two. Cheers. Just to clarify, ‘npp’ is an alias for Notepad++ to open the file once found.
$drv = read-host "Choose drive"
$fname = read-host "File name"
$req = dir -Path $drv -r | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq $fname }
set-location $req.directory
npp $req
From a powershell prompt, use the
gcicmdlet (alias forGet-ChildItem) and-filteroption:This will return an exact match to filename “
hosts“.SteveMustafa points out with current versions of powershell you can use the
-Fileswitch to give the following to recursively search for only files named “hosts” (and not directories or other miscellaneous file-system entities):The commands may print many red error messages like “
Access to the path 'C:\Windows\Prefetch' is denied.“.If you want to avoid the error messages then set the
-ErrorActionto be silent.An additional helper is that you can set the root to search from using
-Path.The resulting command to search explicitly search from, for example, the root of the C drive would be