Bee_Riii
Bee_Riii

Reputation: 1039

powershell - search subdirectories for multiple files

I have a list of file names stored in a text file I would like to search a particular directory and subdirectories and get the full path of all the the files that exist.

Right now I'm using the below code

$FileListPath = "C:\FileList.txt"
$SearchPath = "Y:\Project"
foreach($FileName in Get-Content $FileListPath){(Get-ChildItem -Path $SearchPath -Recurse -ErrorAction SilentlyContinue -Include $FileName).FullName}

This works OK but is slow. I think because for each file it's doing the full search again and again. Is there a faster way to do this?

Also, it's not strictly necessary but I would like to exclude subfolders that have that have include obj as one of the folders. For example: Y:\folder\ I want to be included but y:\Folder\obj\ and Y:\Folder\obj\subfolder I want to be excluded.

Thanks

Upvotes: 0

Views: 1252

Answers (1)

Theo
Theo

Reputation: 61253

The -Include parameter takes a string array of filenames, so you could do this instead:

$FileListPath = "C:\FileList.txt"
$SearchPath   = "Y:\Project"
$exclude      = 'obj'
$fileNames = Get-Content $FileListPath

(Get-ChildItem -Path $SearchPath -Recurse -File -Include $fileNames -ErrorAction SilentlyContinue | 
 Where-Object{ $_.DirectoryName -notmatch $exclude }).FullName

If you have multiple subfolders to skip, set $exclude to:

$exclude = ('obj','skipthis','not_this_one' | ForEach-Object { [Regex]::Escape($_) }) -join '|'

Upvotes: 3

Related Questions