2

I found this batch file password generator:

rem 16 stings pwd

setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set alfanum=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

set pwd=
FOR /L %%b IN (0, 1, 16) DO (
SET /A rnd_num=!RANDOM! * 62 / 32768 + 1
for /F %%c in ('echo %%alfanum:~!rnd_num!^,1%%') do set pwd=!pwd!%%c
)

echo pwd=%pwd%

which I put into a batch file: rand.bat However when I call rand.bat from another batch file, the environment variable pwd is no longer available. How do I get it to persist into the calling batch file?

LotPings
  • 7,231
dacfer
  • 155

1 Answers1

4

Exiting the called batch implies an Endlocal which discards all created local variables.

To overcome this include an Endlocal command and on the same line repeat the set command.

Due to the complex inner working of cmd.exe (which often requires DelayedExpansion) this line is in both scopes and can thus re-create the content of the variable.

rem 16 stings pwd

setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set alfanum=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

set pwd=
FOR /L %%b IN (0, 1, 16) DO (
    SET /A rnd_num=!RANDOM! * 62 / 32768 + 1
    for /F %%c in ('echo %%alfanum:~!rnd_num!^,1%%') do set "pwd=!pwd!%%c"
)

echo pwd=%pwd%
Endlocal & set "pwd=%pwd%" & goto :Eof
LotPings
  • 7,231