0

Unfortunately I'm unable to add comments to an existing StackOverflow article as my rep isn't high enough, so I'll reference the link here: runonce-to-rename-a-computername-with-a-random-name-on-reboot

Why does the batch sample code that LotPings provided always prefix the randomly generated part with the first letter from the character list, e.g. "A"?

Sample code:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set "Chars=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Call :RandChar 26 Name
For /L %%A in (1,1,14) Do Call :RandChar 62 Name
Echo %Name%
Goto :Eof
:RandChar Range Var
Set /A Pnt=%Random% %% %1 & Set %2=!%2!!Chars:~%Pnt%,1!

Result when executed 10 times:

AOyVq8olMi7kZaR
ANyU2MoAzZwTpwo
AYNXqJSGKXgyvca
AFGoCImfNOHuVSz
AHNhxnj9Wyqkqo3
AML6hTrSHK4TFut
AHuinBZCWr5D5NZ
AQYNtXaYMXRdGOb
ARWYXn7YNMQ0cmm
APHdWggSQl5KUhA

How can the code be modified to randomise the starting character too?

MikeD
  • 3
  • 2
  • Without testing anything, I'm going to preemptively blame delayed expansion, because that's usually the source of batch problems. Does using `!random!` instead of `%random%` work? – SomethingDark Nov 13 '17 at 01:07
  • Unfortunately the result appears to be the same. I generated about 15-20 different values and they all still started with A – MikeD Nov 13 '17 at 01:13
  • Put the `set %2` part of the last line on its own line. Something something variable expansion not kicking in when you use `&`. – SomethingDark Nov 13 '17 at 01:16
  • Genius! That worked :D Thank you – MikeD Nov 13 '17 at 01:18

1 Answers1

2
Set /A Pnt=%Random% %% %1 & Set %2=!%2!!Chars:~%Pnt%,1!

should be

Set /A Pnt=%Random% %% %1
Set %2=!%2!!Chars:~%Pnt%,1!

The entire line is parsed, then executed and during the parsing phase, any %var% will be replaced by the value of varat that time. Hence,pntwill be replaced by the value ofpntat the very start, yieldingSet %2=!%2!!Chars:~,1!` and thereafter it will be replaced by the value established on the previous call.

Breaking the line forces the two statements to be executed sequentially.

Magoo
  • 77,302
  • 8
  • 62
  • 84