Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

How to make a series of random letters and numbers with a certain character length in batch?

I am trying to make a program that makes a series of random letters and numbers, upper-case and lower case. Is there a way that I can make this possible for my code?

@echo off
title random password gen
:Start
cls && set choice=0
echo (type 0 to exit)
echo.

echo 1 Random Password
echo 5 Random Passwords
echo 10 Random Passwords

set /p input= quantity:
if %input%==0 exit
if %input%==1 set /a choice=%choice%+1 && goto a
if %input%==2 goto set /a choice=%choice%+5 && goto a
if %input%==3 goto set /a choice=%choice%+10 && goto a
goto start
:a

cls

if %choice%==1 echo your password is %random%
if %choice%==5 echo your 5 passwords are %random%, %random%, %random%, %random%, %random%.
if %choice%==10 echo your 10 passwords are %random%, %random%, %random%, %random%, %random%,%random%, %random%, %random%, %random%, %random%.
pause
echo press any key to continue to menu... && pause nul> && goto menu
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • You are using the conditional execution on success && wrongly. To have two commands on one line use only one &
  • %Random% returns a number between 0 and 32768. See ss64.com/nt/syntax-random.html
  • The var choice is a bit cumbersome as there is an external program choice.exe
  • If you don't store %random% to a var it is lost, next time %random% gets a different value.

The following batch will generate a random Name/Passwort

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set "Chars=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

:: get one char from the first 26(Uppercase) and append to var Name
Call :RandChar 26 Name

:: get 14 chars from all Chars and append to var 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!
Goto :Eof

The same in powerShell is a bit simpler:

$chars = [char[]]"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
$Password = [string](($chars[0..25]|Get-Random)+(($chars|Get-Random -Count 14) -join ""))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...