1

So I wanted to get a simple "this is where we're up to" numbering to show in the host when running a powershell script. I created the below to mess around with this:

$musicList = Get-ChildItem "C:\Users\rlyons\Music" -Recurse -File | Select-Object FullName
$outfile = @{} 
$num = 1
foreach ($sound in $musicList) {
    $file = $sound.FullName.ToString()
    $md5 = Get-FileHash $file -Algorithm MD5
    $outFile.$file += $md5.Hash
    Write-Output "Processed file $num"
    $num ++
}

This works great! Except it gives me:

Processed file 1
Processed file 2
Processed file 3
Processed file 4
Processed file 5

etc etc. What I wanted was for the screen to clear every time it processed a file, so all I wanted to see was the number of the file processed change at the end of the line written to the host.

I tried adding in the good old Clear-Host after the $num ++ and also at the start of the foreach loop, but all I get is a flickering line, and sometimes something partially ledgible. Yes, this is down to how fast the files are being processed, but I was wondering if there is a trick to this? To keep the Processed file bit continously on screen, but have the number increment upwards?

Even better would be if it didn't clear the screen, so you could see all previously written outputs but have this one line refresh? Is this possible?

Note: I'm trying this in VS Code, Powershell 5.1

Ross Lyons
  • 161
  • 4
  • 14

1 Answers1

4

Per the comments, Write-Progress is a much better fit for this because it gives you the output you want but without affecting the actual output stream of the script (e.g what is returned to any potential follow on command you might write).

Here's how you might want to use Write-Progress that will also show the percentage of completion:

$musicList = Get-ChildItem "C:\Users\rlyons\Music" -Recurse -File | Select-Object FullName
$outfile = @{} 
$num = 1
foreach ($sound in $musicList) {
    $file = $sound.FullName.ToString()
    $md5 = Get-FileHash $file -Algorithm MD5
    $outFile.$file += $md5.Hash
    Write-Progress -Activity "Processed file $num of $($musiclist.count)" -PercentComplete ($num / $musiclist.count * 100)
    $num ++
}
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • 1
    So this works perfectly, apart from not in Visual Studio Code, which is a shame! I'll post it on their Git page. Works as expected in the ISE. – Ross Lyons Nov 23 '17 at 19:37
  • Thats probably related to the issue where there clear-host function doesn't actually clear the console. Good job on both the script and the follow up to their git page – Snak3d0c Nov 23 '17 at 20:28