Skip to main content

How to Generate a Random Password in Batch Script

Automatically generating a random password, or a one-time setup code, is a common requirement for user account creation scripts or temporary file protection. While the Windows Command Line doesn't have a specific generate-password command, it does have a %RANDOM% variable. By picking characters from a pre-defined "Bucket" using a random index, we can build a strong, customized password.

In this guide, we will demonstrate how to build a random password generator using a character pool and a loop.

The Strategy: The Pick-and-Pack Loop

  1. Define a string containing all allowed characters (Letters, Numbers, Symbols).
  2. Set the desired password length.
  3. In a loop, generate a %RANDOM% number.
  4. Fit that number into the range of your character pool.
  5. Extract that character and append it to your password.

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: 1. Define the character pool (Bucket)
:: Note: %% produces a literal %% in the pool. The ^ escapes the caret itself.
set "chars=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%%%%^^&*"

:: Get the length of the bucket
set "bucket_len=0"
set "temp_bucket=!chars!"
:calc_len
if defined temp_bucket (
set "temp_bucket=!temp_bucket:~1!"
set /a "bucket_len+=1"
goto calc_len
)

echo Character pool length: !bucket_len!

:: 2. Config
set "pass_len=12"
set "password="

echo Generating a !pass_len!-character password...

:: 3. The Generator Loop
for /L %%i in (1,1,!pass_len!) do (
:: Get a random index within the bucket range
set /a "idx=!RANDOM! %% !bucket_len!"

:: Pick the character at that index
for %%j in (!idx!) do set "char=!chars:~%%j,1!"

:: Append to password
set "password=!password!!char!"
)

echo.
echo ==========================================
echo NEW PASSWORD: !password!
echo ==========================================
pause
endlocal
warning

The %RANDOM% variable in Batch is a pseudo-random number generator seeded from the system clock. It is adequate for temporary setup codes and general-purpose scripts, but it is not cryptographically secure. Do not use this method for high-security credentials like service accounts, encryption keys, or banking systems. Use PowerShell's Get-Random -InputObject with a [System.Security.Cryptography.RandomNumberGenerator] source or a dedicated secrets manager instead.

Why Generate Passwords in Batch?

  1. User Onboarding: Automatically generating a temporary password for a newly created Active Directory or local computer user.
  2. File Security: Generating a unique, random string to use as a password for an encrypted .zip backup.
  3. Setup Keys: Providing a random "Install Key" at the end of a software deployment script.

Important Considerations

  1. Special Characters: If your password contains &, |, ^, or %, you must be careful when using it in other commands, as these are "Poison characters" in Batch. Always wrap your password variable in delayed expansion (!password!) or careful quoting when passing it to other scripts.
  2. Modulo Bias: %RANDOM% produces values from 0 to 32,767. When the pool size does not evenly divide 32,768, some characters have a slightly higher chance of being selected. For a pool of ~70 characters, the bias is negligible in practice.
  3. Character Pool Escaping: Defining the pool string requires special attention. % must be doubled (%%) to produce a literal percent sign, and ^ must be escaped (^^) so it survives parsing. Verify the pool length output to confirm all characters are present.

Best Practices

  1. Exclude Ambiguous Characters: To make passwords easier for humans to read, many scripters choose to exclude l (lowercase L), I (uppercase I), 0 (zero), and O (uppercase O).
  2. Complexity Requirements: If you need a "Strong" password (must have at least one capital and one number), you may need to add a "Check and Retry" loop at the end to verify the generated string meets those criteria.

Conclusion

Generating a random password in Batch is a creative application of string manipulation and random logic. By building your own custom "Bucket" of characters, you can generate passwords that meet your specific length and complexity requirements perfectly. This ability ensures your automation scripts remain secure and capable of handling sensitive setup tasks with ease.