mercredi 4 juillet 2018

Generate random string for Windows batch files without dependencies

Background

Looking for the fastest way to generate random strings, purely with Windows 7 batch commands.

Constraints

No external dependencies, such as uuidgen, PowerShell, or VBA.

Dependencies on default system commands, such as ping is acceptable.

Problem

The following code generates a random 32-character string:

@echo off
rem Delay in milliseconds for random number generator to recycle.
ping localhost -n 1 -w 1 > nul

break on
setlocal enabledelayedexpansion

set "xGUID="
for /L %%n in (1,1,32) do (
  set /a "hex=!RANDOM! %% 16"
  if "!hex!"=="10" set "hex=A"
  if "!hex!"=="11" set "hex=B"
  if "!hex!"=="12" set "hex=C"
  if "!hex!"=="13" set "hex=D"
  if "!hex!"=="14" set "hex=E"
  if "!hex!"=="15" set "hex=F"
  set "xGUID=!xGUID!!hex!"
)
echo %xGUID%
endlocal & if not "%~1"=="" set "%~1=%xGUID%"
exit /b

It's fairly fast, except for the delay, which is required so that successive calls (e.g., in a tight loop) do not re-generate the same number.

Problem

The following code produces the same string twice:

for /f "delims=" %a in ('call guid.bat') do ( @echo %a) && for /f "delims=" %a in ('call guid.bat') do ( @echo %a)

Increasing the number of requests from 1 to 2 solves the issue because a sufficient delay is introduced between calls:

ping localhost -n 2 -w 1 > nul

Calling the batch file twice in rapid succession now produces two different strings, albeit with a delay between calls.

Strangely, the following code generates two different strings without having to introduce any delay:

call guid.bat && call guid.bat

Adding a loop changes the behaviour.

Questions

  • Why do the for loops return the same value when run in rapid succession, but calling the batch file directly (i.e., outside of loops) returns two different values?
  • What needs to change for the for loops to return different values when run in rapid succession (i.e., no delay)?



Aucun commentaire:

Enregistrer un commentaire