Is there a batter way to display progress of Get-ChildItem with Write-Progress

Hello,

I wrote some code to display progress of running “Get-ChildItem” command but In my opinion it is to big for such simple task. Could it be wrote in simpler way?

$path = "C:\users\$env:USERNAME\Downloads"
$numberOfFiles = Get-ChildItem $path -Recurse | Measure-Object -property Length | select-object -ExpandProperty Count

$script:iterator = 1;

Get-Childitem   -Recurse -Path  $path | `
                Format-Table -Autosize -Property `
                    Mode, `
                    LastWriteTime, `
                    Length, `
                    @{Name="Nazwa";Expression={
                        $_.Name;
                        Write-Progress -Activity "Scanning directory " -Status "file: $script:iterator of $numberOfFiles"  -percentComplete ($script:iterator / $numberOfFiles * 100);
                        $script:iterator ++;
                        Start-Sleep -Seconds 0.5
                        }
                    }

Despite of some minor issues and a little bit bad style … I assume it works for you or doesn’t it? :wink:

What’s the actual purpose of this code? Mostly we try to make our code to run as fast as possible. Therefore we wouldn’t use Start-Sleep if it’s not needed. But I assume you included it to actually see the effect of Write-Progress, right? I would write it probably this way:

$path     = "$env:USERPROFILE\downloads"
$fileList = Get-ChildItem $path -Recurse
$counter  = 1

foreach ($file in $fileList) {
    Write-Progress -Activity "Scanning directory '$($path)'" -Status "file: $counter of $($fileList.Count)"  -percentComplete ($counter / $($fileList.Count) * 100)
    $counter ++
    # Start-Sleep -Milliseconds 500
    [PSCustomObject]@{
        Name          = $file.Name
        Mode          = $file.Mode
        LastWriteTime = $file.LastWriteTime
        Length        = $file.Length
    }
}

I’d recommend to read “The Unofficial PowerShell Best Practices and Style Guide

@Olaf - Thank you for your reply :slight_smile:

Yes, you have right - Start-Sleep was just to see how code is working.

Code works quite well for my purposes, but I had some feeling that it can be written in the better way :wink:

I’m beginner and I’m trying to improve my skills. Also thx for link to Best Practices. I’ll try to apply to them.