Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Speedy PowerShell file search on Windows
<#
.Synopsis
Performs a basic filename search throughout a directory
.DESCRIPTION
Performs a basic filename search throughout a directory and returns matching file names
.EXAMPLE
Search-Filename -Path "C:\Windows\System32" -Pattern "*.dll"
.EXAMPLE
Search-Filename "document.txt" -Recurse
#>
function Search-Filename
{
param(
[Parameter(Mandatory=$false)]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[string]
$Path = ".\",
[Parameter(Mandatory=$true,Position=0)]
[string]
$Pattern,
[Parameter(Mandatory=$false)]
[switch]
$Recurse
)
if($Recurse)
{
$SearchOption = [System.IO.SearchOption]::AllDirectories
}
else
{
$SearchOption = [System.IO.SearchOption]::TopDirectoryOnly
}
$IllegalChars = [char[]]'^\/:"<>|'
foreach($c in ([char[]]$Pattern))
{
if($IllegalChars -contains $c)
{
throw [System.IO.IOException]"$Pattern contains illegal character $c"
return $false
}
}
$Directory = Get-Item -Path $Path
try{
[System.IO.Directory]::GetFiles($Directory.FullName,$Pattern,$SearchOption)
}
catch{
Write-Error $_
}
}
@gravejester

This comment has been minimized.

Copy link

commented Oct 13, 2014

I have experimented with a similar approach to speed up searching for files and folders in PowerShell, but I had to abandon this approach, as it fails when it hits a folder it can't read. And it just fails, it won't continue :( I have managed to code around it, but by then the speed was actually worse than just using Get-ChildItem.

@IISResetMe

This comment has been minimized.

Copy link
Owner Author

commented Oct 16, 2014

Yes, this implementation suffers from that as well :( ... I might try something like this: https://social.msdn.microsoft.com/Forums/vstudio/en-US/ae61e5a6-97f9-4eaa-9f1a-856541c6dcce/directorygetfiles-gives-me-access-denied (The Stack example)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.