Home > other >  How to find a file from files via PowerShell?
How to find a file from files via PowerShell?

Time:11-28

I had an excel script to search for files in a command.

I found this example on the forum, the statement says that to search for a file by name, you need to write down the name and send (*) but when requested, it does not find anything

Get-ChildItem -Path "C:\\Folder\\test\*"

What can I do to simplify the code and make it much faster. Wait 10 minutes to find a file out of 10000. this is very long

I have a folder with 10,000 files, and excel searches through VBA for a script in almost 2-3 seconds. When to script in PowerShell via


$find = Get-ChildItem -Path "C:\\Folder"
for ($f=0; $f -lt $find.Count; $f  ){
$path_name = $find\[$f\].Name
if($path_name-eq 'test'){
Write Host 'success'
}
}

ut it turns out sooooooo long, the script hangs for 10 minutes and does not respond, and maybe he will be lucky to answer. How can I find a file by filter using

Get-ChildItem

CodePudding user response:

To make your search faster you can use Get-ChildItem filter.

$fileName = "test.txt"

$filter = "*.txt"

$status = Get-ChildItem -Path "C:\PS\" -Recurse -Filter $filter | Where-Object {$_.Name -match $fileName}

if ($status) {
Write-Host "$($status.Name) is found"
} else {

Write-Host "No such file is available"
}

You could also compare the speed of searching by using Measure-Command

CodePudding user response:

  • If the disk the data is on is slow then it'll be slow no matter what you do.

  • If the folder is full of files then it'll also be slow depending on the amount of RAM in the system. Less files per folder equals more performance so try to split them up into several folders if possible. Doing that may also mean you can run several Get-ChildItems at once (disk permitting) using PSJobs.

  • Using several loops to take take care of a related problem usually makes the whole thing run "number of loops" times as long. That's what Where-Object is for (in addition to the -Filter, -Include and -Exclude flags to Get-ChildItem`).

  • Console I/O takes A LOT of time. Do NOT output ANYTHING unless you have to, especially not inside loops (or cmdlets that act like loops).

For example, including basic statistics:

$startTime = Get-Date
$FileList  = Get-ChildItem -Path "C:\Folder" -File -Filter 'test'
$EndTime   = Get-Date

$FileList

$AfterOutputTime = Get-Date

'Seconds taken for listing:'
(EndTime - $startTime).TotalSeconds

'Seconds taken including output:'
($AfterOutputTime - $StartTime).TotalSeconds
  • Related