tags:

views:

45

answers:

3

Searched everywhere for this but no luck. I wanted to write a small script that searched for an exact file name, not just 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
+1  A: 

Assuming you have a Z: drive mapped:

Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
George Howarth
Thank you. Elaborate answer, worked perfectly. Learned a few things too :)
gavin19
+2  A: 

From a command prompt at the root:

gci -recurse -filter "hosts"

Is only going to return an exact match to filename "hosts" - and a lot of red messages where I need elevated permissions (-:

Basically the -filter is, I think, the key.

Murph
Ah yes, `-Filter` is faster for this. He said he's looking for files so you'll need to add `? { !$PsIsContainer }`.
George Howarth
Thank you, exactly what I was after :)
gavin19
A: 

I use this form for just this sort of thing:

gci . hosts -r | ? {!$_.PSIsContainer}

. maps to positional parameter Path and "hosts" maps to positional parameter Filter. I highly recommend using Filter over Include if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include.

Keith Hill
Cheers, works great. Much appreciated sir!
gavin19