variable in cycle

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
JustAlex
Posts: 1
Joined: 09 Jun 2010 02:57

variable in cycle

#1 Post by JustAlex » 09 Jun 2010 03:07

hello!
i have the next code:

Code: Select all

FOR /f "tokens=1 usebackq delims=," %%a in (`dsquery computer "OU=Users PC,OU=Computers,OU=Office,DC=gpi,DC=domain,DC=com"`) do (
rem set /a zzz=%zzz%+1
set zzz=%%a
   echo %zzz%
   echo %%a

)
pause

when it's running, i get the right value of %%a for all steps in cycle,
but %zzz% is always empty...

what's wrong?
have i to set zzz as global variable? how?
or the syntax for set zzz=%%a is incorrect?

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: variable in cycle

#2 Post by jeb » 09 Jun 2010 08:43

Hi,

zzz is not empty, but the way you try to print it fails.

The reason is the expansion phase of the %zzz%.
The %zzz% is only once expanded, at the beginning of the block ().
So you only see the value before you entered the block.

If you want to use the current value use the delayed expansion syntax.

Code: Select all

set EnableDelayedExpansion 
set zzz=Before
FOR /f "tokens=1 usebackq delims=," %%a in (`dsquery computer "OU=Users PC,OU=Computers,OU=Office,DC=gpi,DC=domain,DC=com"`) do (
rem set /a zzz=!zzz!+1
set zzz=%%a
   echo current=!zzz!, and %zzz%
   echo %%a
)
pause


jeb

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: variable in cycle

#3 Post by aGerman » 09 Jun 2010 10:22

@jeb
First line:
setlocal EnableDelayedExpansion
:wink:

Regards
aGerman

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: variable in cycle

#4 Post by jeb » 10 Jun 2010 11:08

You got me. :)

You can see, I haven't tested it.

jeb

Post Reply