how to search files and display progress bar in powershell

I am currently coding in Powershell, and I am now looking for a way to display the progress bar while searching the system for documents. I am using Get-ChildItem instead of a loop, since it is much faster and more efficient than a loop. I have already figured out how to use the Get-ChildItem cmdlet, but I need help figuring out how to implement the progress bar into it. Here is an example of the code I am using, so it is easier to understand:

Set-Variable $Loading 0
Write-Progress -Activity "Collecting Files For Removal..." -CurrentOperation "Collecting User Files..." -PercentComplete $Loading
Get-ChildItem C:\Users\firea\ -Filter *.D11 -ErrorAction SilentlyContinue -Force

1 answer

  • answered 2017-11-15 21:49 TheMadTechnician

    So, what it sounds like is that you want to show the user a progress bar that displays X% completed, but until you run Get-ChildItem you don't know how many total items there are, so you can't really tell how close to done you are. Let me put this another way.

    Say you go out and take a hike. You do a quick search online for local trails, find one, and off you go! You know where the trail starts, and you know that there's a corndog stand at the end of it that you're looking forward to sampling. 12 minutes into your hike your girlfriend calls you and asks you to bring her back a corndog too! Sure, no problem, it might be cold by the time it gets to her, but you can do that. Then she asks how long it'll take,and you realize that you have no idea. You're 12 minutes in, but until you get to that corndog stand you have no idea if it's another 3 minutes along, or 35 minutes along, because you don't know how long the trail is.

    Ok, same scenario, but this time you see the zip-line that goes over the trail and take that first. Sure, you don't know what all the details of the trail are, but you get a good idea of about how long it is, and a general idea of the trail. This time when your girlfriend calls you can tell her it'll be about 20 minutes, because you're about 12 minutes in, there's about 4 minutes to the stand, and then another 16 minutes back out to where she's at.

    Same idea would be applied to your script. In order to give the user even a rough estimate of progress you have to have a rough idea of what you're looking at. Are you searching 1 folder? Well, there's really no good way to get a rough estimate of one folder, but it shouldn't take that long that you'd need a progress bar. Now if you're searching an entire drive you could use the -directory parameter of Get-ChildItem, find out how many folders there are, and give the user progress based on how many folders you've searched.