0

I am trying to redirect command output to variable using file as intermediary. I am able to redirect command output to file and but unable to read content of file into variable.

Batch File Script

echo off

pushd C:\Software
set TEMP_DIR=C:\Users\prade\Softwares

for /D %%i in (*) do (
    pushd "%%i"
    echo %TIME% > %TEMP_DIR%\a.log
    type %TEMP_DIR%\a.log
    for /f "delims=" %%x in (%TEMP_DIR%\a.log) do set duration=%%x
    echo %%i  %duration%
    popd
)
popd
echo on

I gives me below output

C:\Users\prade>echo off
 7:36:47.86
AutoHotKey
 7:36:47.86
cygwin64
 7:36:47.86
ffmpeg-20150518-git-451be67-win64-static
 7:36:47.86
mtn-200808a-win32
 7:36:47.86
ProcessExplorer
 7:36:47.86
tools

As you see there is nothing after directory name but type giving me content of file.

If I echo %duration% after batch file terminate in same cmd window, it gives me last time back.

What I am doing wrong?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
kr.pradeep
  • 115
  • 8
  • 3
    you fell into the [delayed expansion trap](http://stackoverflow.com/a/30284028/2152082). – Stephan May 20 '15 at 11:50
  • @Stephan, Thanks. There is always something new stuff to learn. :) – kr.pradeep May 20 '15 at 12:08
  • @Stephan, does that mean I should use `!` all the time instead of `%`, is there any harm, performance impact of using `!` instead of `%` something like that? – kr.pradeep May 20 '15 at 15:29
  • Found this [link](http://ss64.com/nt/delayedexpansion.html) that explain what `setlocal enableDelayedExpansion` do. Based on that I assume it should be used all the time, unless we have specific need to expand at parse time. Correct? – kr.pradeep May 20 '15 at 15:42
  • No, just the other was round: use delayed variables only, if you have specific need to expand at execution time. There are some interesting links in the answers and comments of [this question](http://stackoverflow.com/questions/14354502/difference-between-variable-and-variable-in-batch-file) – Stephan May 20 '15 at 15:45

2 Answers2

1
@echo off

pushd C:\Software
set "TEMP_DIR=C:\Users\prade\Softwares"

setlocal enableDelayedExpansion
for /D %%i in (*) do (
    pushd "%%i"
    echo %TIME% > "%TEMP_DIR%\a.log"
    type %TEMP_DIR%\a.log
    for /f "usebackq delims=" %%x in ("%TEMP_DIR%\a.log") do set "duration=%%x"
    echo %%i  !duration!
    popd
)
popd
echo on
npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

Add SETLOCAL EnableDelayedExpansion just below ECHO OFF and access duration with !duration! instead of %duration%.

MichaelS
  • 5,941
  • 6
  • 31
  • 46