Vinit Sankhe
Vinit Sankhe

Reputation: 19885

Nested for loop with if statement in batch file

I know this question might have already been discussed a thousands of times but I dont know what am I doing wrong!

I have the following bat file script that tries to perform a memory dump based on PID of all the current processes matched by the %PROCNAME% variable. It seem to perform what I need upto the point where I echo the %DUMFILENAME%. Here it prints the PID of the previous iteration's PID variable ...

E.g. If I have 3 notepad instances (with PIDs 1, 2, 3) running and I run the following bat. I get following output on command prompt:

"Current PID is 1"

C:\Documents and Settings\userme\Local Settings\Application Data\notepad\notepad.exe_Thu 03222012204843.02.dmp

"Current PID is 2"

C:\Documents and Settings\userme\Local Settings\Application Data\notepad\notepad.exe_1_Thu 03222012204843.02.dmp

"Current PID is 3"

C:\Documents and Settings\userme\Local Settings\Application Data\notepad\notepad.exe_2_Thu 03222012204843.02.dmp

My bat script:

@echo off
SETLOCAL EnableDelayedExpansion
SET PROCNAME=notepad.exe
FOR /F "tokens=1 delims=," %%A in ('tasklist /FI "IMAGENAME eq %PROCNAME%" /FO LIST') DO (
      set "maintoken=%%A"
      Call:InnerToken !maintoken!)
pause
goto :end
:InnerToken
set innertoken=%1
IF "%innertoken%"=="PID:" (
      FOR /F "tokens=1,2 delims=:" %%B in ("%innertoken%") DO (
         set "res=%~n2"
         echo "Current PID is !res!"
         SET "DUMPFILENAME=%USERPROFILE%\Local Settings\Application Data\Notepad\%PROCNAME%_!res!_%date:/=%%time::=%.dmp"
         echo %DUMPFILENAME%
         )
      )
:end

Any help would be greatly appreciated...

Upvotes: 0

Views: 3733

Answers (1)

Joey
Joey

Reputation: 354496

Use

echo !DUMPFILENAME!

instead.

Which surprises me though, as you seem to already know that you need delayed expansion when setting and using variables in blocks.

Upvotes: 2

Related Questions