Skip to main content

How to Generate a Random Alphanumeric String in Batch Script

Generating a random alphanumeric string (a mix of letters and numbers) is useful for creating unique temporary filenames, transaction IDs, or secure tokens. Similar to generating a password, this task involves picking characters from a restricted pool (A-Z, a-z, 0-9) using the %RANDOM% variable. By excluding symbols, you ensure the string is “web-safe” and won’t break command-line syntax.

In this guide, we will demonstrate how to generate alphanumeric strings of any length.

The Strategy: The Character Pool Loop

  1. Define a pool of all 62 alphanumeric characters.
  2. Determine the desired string length.
  3. Loop X times, picking a random character from the pool each time.
  4. Join the characters together into a single string.

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: 1. Define the Alphanumeric Character Pool
set "pool=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
set "pool_size=62"

:: 2. Configuration
set /p "len=Enter desired string length (e.g., 8): "
if not defined len (
echo Error: length cannot be empty.
exit /b 1
)
set /a "len=len"

if %len% LSS 1 (
echo Error: length must be >= 1.
exit /b 1
)

set "result="

echo Generating a %len%-character alphanumeric string...

:: 3. The Generation Loop
for /L %%i in (1,1,%len%) do (
:: Get a random index (0 to 61)
set /a "idx=!RANDOM! %% pool_size"

:: Extract the character at that specific index
for %%A in (!idx!) do set "char=!pool:~%%A,1!"

:: Append character to our result
set "result=!result!!char!"
)

echo.
echo ==========================================
echo GENERATED STRING: !result!
echo ==========================================
pause
endlocal
warning

Batch %RANDOM% is pseudo-random (not cryptographically secure). If you need security-grade tokens/keys, generate them with PowerShell using System.Security.Cryptography.RandomNumberGenerator.

Why Use Alphanumeric Strings?

  1. Unique Filenames: When your script creates temp files, using a random string like TMP_4f9a2b.txt prevents your script from overwriting existing files if multiple instances are running.
  2. Session Tokens: Generating a simple ID for a user session in an interactive menu or a network diagnostic tool.
  3. Code Verification: Creating short, easy-to-read “verification codes” for users to type in during a setup phase.

Important Considerations

  1. Duplicate Stripping: If your string is very short (e.g., 3 characters), there is a small chance you might generate the same string twice. For truly unique IDs, use a longer length (8+ characters) or check against existing files before committing.
  2. Case Sensitivity: If your target system is case-insensitive, consider using only uppercase or only lowercase letters to avoid confusion.
  3. Pseudo-Randomness: Like all Batch %RANDOM% functions, this is not cryptographically secure, but it is perfect for automation and organizational tasks.

Best Practices

  1. Include the Date: To ensure absolute uniqueness across time, prepend the current date/time to your random string: Log_%DATE%_%result%.txt.
  2. Environment Cleaning: Always use setlocal at the start of your script so your pool and result variables are cleared when the script finishes.

Conclusion

Generating random alphanumeric strings provides a robust way to manage unique data in your automation scripts. By picking from a clean pool of letters and numbers, you create strings that are both human-readable and safe for use in filenames, URLs, and database keys.