Nov 222008

Ever wondered how we can generate random numbers in a batch file. Yes, I am talking about our good old faithful friend ‘.bat’ file. Why do I need one? You may ask! I had to generate a unique filename everytime because I had to backup a folder before I updated it.

So tell us is there one? Yes use ‘random’, it’s a built in command which generates a random number when you invoke it. Every time a unique one! So if you type in ‘random’ at a command line and then press enter, you’ll get an error because it’s not an independent executable, but a feature that is built into command prompt to help generate random numbers. So how will I get a random number? This is how I do it…

echo %random%

Make a random directory….

mkdir C:\Nibu_%random%

If Command Extensions are enabled, then there are several dynamic environment variables that can be expanded but which don’t show up in the list of variables displayed by SET.  These variable values are
computed dynamically each time the value of the variable is expanded. If the user explicitly defines a variable with one of these names, then that definition will override dynamic ones like %random%.

For more information type “set /?”

To enable command extensions open up regedit and then navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor\EnableExtensions
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions

and set value to 1. If not present then add one REG_DWORD value with an identical name and value set to 1.