Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created October 7, 2014 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IISResetMe/b179d290368990a53e16 to your computer and use it in GitHub Desktop.
Save IISResetMe/b179d290368990a53e16 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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