Msprg
Msprg

Reputation: 351

numbering variables, when valid path is found

Maybe I did not give it a good title, anyway

Hi,

I writing some script in batch, and need help.

with FOR i checking all possible drives letters A-Z and when on some of that will be found X:\Users\Public\Desktop , then save this letter to numbered variable 1_windrive, 2_windrive, 3_windrive etc........

but my code does not work, and i do not know where is problem.

Here is the code:

@echo off
setlocal EnableDelayedExpansion
set number=1
if not defined !number!_windrive (
for %%p in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist %%p:\Users\Public\Desktop (
set !number!_windrive=%%p
echo !number!%_windrive%
set /a "number=%number%+1"
)
pause

solution code:

@echo off
setlocal EnableDelayedExpansion
set number=1
if not defined windrive_!number! (
for %%p in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist %%p:\Users\Public\Desktop (
set windrive_!number!=%%p
CALL echo %%windrive_!number!%%
set /a number=number+1
)
)
echo %windir%
echo %windrive_1%
echo %windrive_2%
echo %windrive_3%
echo %windrive_4%
echo %windrive_5%
pause

Upvotes: 0

Views: 42

Answers (1)

Magoo
Magoo

Reputation: 80113

set windrive_!number!=%%p
CALL echo %%windrive_!number!%%
set /a number=number+1

The easy way to list the windrive variables set is

set windrive

As squishy says, starting a variable with a numeric is likely to cause cmd syntactic apoplexy.

%var% means "the value of var when the code-block was started" so it will remain unchanged as the loop progresses. !var! means the value as it changes within the loop.

quotes are not required for a set/a, neither is % nor ! - the variable-name itself means "the run-time value of the variable" (ie as it changes within the loop) and this is regardless of whether or not enabledelayedexpansion has been invoked.

[edit - fixed echo within for loop]

Upvotes: 1

Related Questions