Powershell script to locate specific file/file name?
From a powershell prompt, use the gci
cmdlet (alias for Get-ChildItem
) and -filter
option:
gci -recurse -filter "hosts"
This will return an exact match to filename "hosts
".
SteveMustafa points out with current versions of powershell you can use the -File
switch to give the following to recursively search for only files named "hosts
" (and not directories or other miscellaneous file-system entities):
gci -recurse -filter "hosts" -File
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 -ErrorAction
to be silent.
gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue
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
gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"
Assuming you have a Z:
drive mapped:
Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
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
.