Created
October 7, 2014 11:03
-
-
Save IISResetMe/b179d290368990a53e16 to your computer and use it in GitHub Desktop.
Speedy PowerShell file search on Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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 $_ | |
} | |
} |
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
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.