Is there something like the GNU locate command in PowerShell?
Is there an equivalent of the GNU locate
command in Windows 7/8?
locate
can take as input a file name and gives as output all the paths where files named similarly to input are, e.g.:
locate file-with-long-name.txt
/var/www/file-with-long-name.txt
No, there is not a Windows cmd or PowerShell builtin equivalent to Linux/GNU's locate
command. However, functional equivalents include cmd.exe's dir /s
as described by JKarthik
, and these PowerShell options:
PS> Get-ChildItem -Recurse . file-with-long-name.txt
Note the use of .
, telling PowerShell where to begin the search from. You can, of course, shorten when typing at the command line:
PS> gci -r . file-with-long-name.txt
I do this a lot, so I added a function to my profile:
PS> function gcir { Get-ChildItem -Recurse . @args }
PS> gcir file-with-long-name.txt
This allows wildcards, similar to locate
:
PS> gcir [a-z]ooo*.txt
See help about_Wildcards
for more details. That can also be written with Where-Object
like this:
PS> gcir | where { $_ -like "[a-z]ooo*.txt"}
locate
has an option to match with regexes. So does PowerShell:
PS> gcir | where { $_ -match "A.*B" }
PowerShell supports full .NET Regular Expressions. See about_Regular_Expressions
.
You can do other types of queries, too:
PS> gcir | where { $_.Length -gt 50M } # find files over 50MB in size
Performance of these approaches is slow for large collections of files, as it just searches the filesystem. GNU locate
uses a database. Windows now has a searchable database, called Windows Desktop Search. There is an API to WDS, which someone has wrapped with a PowerShell cmdlet, here: http://www.codeproject.com/Articles/14602/Windows-Desktop-Search-Powershell-Cmdlet, allowing things like:
PS> get-wds “kind:pics datetaken:this month cameramake:pentax”
with much better performance than Get-ChildItem
, and this kind of rich query (and awkward syntax). Also, note that curly quotes work fine in PowerShell, so no need to edit that sample when copy/pasting it.
Maybe someone will find (or write) PowerShell cmdlets that allow idiomatic queries to WDS.
For a PowerShell solution, try this:
Get-ChildItem -Filter "file-with-long-name.txt" -Recurse
This returns all files that match the given name in the current directory and its subdirectories.
The -Filter
parameter accepts wildcards. If the current directory contains system files that you don't have access to, add -ErrorAction SilentlyContinue
to suppress errors.
For more information, see Get-Help Get-ChildItem
.