Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: SET variable not working in an 'if' or 'for' loop of windows batch script  (Read 28475 times)

0 Members and 1 Guest are viewing this topic.

vij_guy

  • Guest
Once I get into a 'if' block or 'for'  loop in a batch script, it doesn't recognize the SET variable. I found something about CMD /V:ON to enable the delayed execution in a batch script; but then how would you run it in a batch script. When I enabled the CMD /V, the batch script won't run any further beyond that.

I finally had to change the logic using GOTO and do away with getting into an 'if' block. Any solution to this?

Dusty



    Egghead

  • I could if she would, but she won't so I don't.
  • Thanked: 75
  • Experience: Beginner
  • OS: Windows XP
Re: SET variable not working in an 'if' or 'for' loop of windows batch script
« Reply #1 on: February 18, 2008, 03:23:29 PM »
Welcome to the CH forums.

Please read >>this<< and post your script.

One good deed is worth more than a year of good intentions.

Dias de verano

  • Guest
Re: SET variable not working in an 'if' or 'for' loop of windows batch script
« Reply #2 on: February 19, 2008, 03:05:18 AM »
It is possible to enable delayed expansion within a script, using the setlocal command with the enabledelayedexpansion modifier.

This first script won't display values for %number% and %answer%, because those variables are expanded at runtime, and will be empty.

Quote

@echo off
for %%N in (1 2 3 4) do (
   set number=%%N
   echo number=%number%
   )

set count=11
if "%count%"=="11" (
  set answer=yes
  echo answer=%answer%
  )


This second script will work because delayed expansion is enabled and because !number! and !answer! have exclamation marks instead of percent signs.

Once you are outside the IF block or loop you can use the variables with % signs and they will show up.

Quote

@echo off
setlocal enabledelayedexpansion
for %%N in (1 2 3 4) do (
   set number=%%N
   echo number=!number!
   )

set count=11
if "%count%"=="11" (
  set answer=yes
  echo answer=!answer!
  )

« Last Edit: February 19, 2008, 06:49:44 AM by Dias de verano »