2

How can I show the progress of a long running operation in windows batch (cmd) file in percentage? Can you share some example code?

Sandeep Datta
  • 28,607
  • 15
  • 70
  • 90

2 Answers2

0

Here is how...

Note: This code is a slightly modified version of this answer.

@echo off

for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"

FOR /L %%n in (1,1,10) DO (
    call :show_progress %%n 10
    ping localhost -n 2 > nul
)

echo Done!
exit /b

:show_progress
setlocal EnableDelayedExpansion
set current_step=%1
set total_steps=%2
set /a "progress=(current_step * 100) / total_steps"

set /p ".=Progress: !progress!%%!CR!" <nul

if !progress! equ 100 echo.

exit /b
Community
  • 1
  • 1
Sandeep Datta
  • 28,607
  • 15
  • 70
  • 90
  • I recommend to state `if !progress! EQU 100` to do a true numeric comparison as `==` forces string comparison... – aschipfl Mar 29 '16 at 10:21
  • Just saying it is good coding practice to match every `setlocal` with an `endlocal` for readability. @SandeepDatta that is a interesting that `!cr!`puts the carriage return stored in variable into the output stream but `%cr%` does not. Do you know why the latter does not work? – Skip R Apr 02 '16 at 20:06
  • @SkipR See following link for an explanation of why sometimes ! is needed instead of %: http://ss64.com/nt/delayedexpansion.html – Sandeep Datta Apr 03 '16 at 06:07
  • Changing code to `set /p ".=Progress: %progress%%%!CR!" – Skip R Apr 03 '16 at 22:21
0

An example would be scanning a large file/database, showing progress instead of a blinking cursor, for ages!

set c=<no. of lines in file>
for /l %i in (1,1,%c%) do cls & set /p="Scanning for target ... "<nul & (set /a per=%i00/%c% >nul & echo !per!%)& ping 127.0.0.1 -n 2 > nul & REM when target found, send agents to greet
echo Complete.

The code in brackets () are for progress percentage.

Tested in Win 10 CmD>

Zimba
  • 2,854
  • 18
  • 26