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?

5
  • 3
    you fell into the delayed expansion trap. Commented May 20, 2015 at 11:50
  • @Stephan, Thanks. There is always something new stuff to learn. :) Commented May 20, 2015 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? Commented May 20, 2015 at 15:29
  • Found this link 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? Commented May 20, 2015 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 Commented May 20, 2015 at 15:45

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.