1

I am trying to write a batch file that takes the time taken of a command and converts it into hours, minutes and seconds.

Here's what I've got:

@echo off

set /a sec=0
set /a min=0
set /a hrs=0
for /f %%G in ('ping localhost -n 100 >nul') do (
    ping localhost -n 1 >nul
    set /a sec+=1
    if %sec%==60 ( 
        set /a min+=1
        set /a sec=0
    )
    if %min%==60 (
        set /a hrs+=1
        set /a min=0
    ) 
)
echo Time taken: %hrs%:%min%:%sec%.

I keep getting a ") was unexpected at this time." error. The FOR loop definitely works and it is just the IF statements that are the problem.

I have tried using the EQU operator and adding quotation marks to no avail. Could anybody help?

Also, I read somewhere that the set operator may not work under an IF statement - is this true?

user3295336
  • 51
  • 10

1 Answers1

0

You need to use this at the top of your batch file

setlocal enabledelayedexpansion

and the !sec! and !min! syntax instead of using % to change and use variables within a loop.

Without delayed expansion you can't change a variable using set within a loop and also use the variable within the same loop, or nested set of loops.

foxidrive
  • 40,353
  • 10
  • 53
  • 68