Home > database >  Write Multiple Variables in one txt document Batch
Write Multiple Variables in one txt document Batch

Time:12-08

Is it possible to write multiple Variables in one .txt document in batch? I would like to make a random password generator where you first have to say how many characters the password must be long and then the password gets generated and put in a .txt file

My idea was that first (after you said how long the password should be) a random number is generated (for the start 1, 2 or 3 (1 = a, 2 = b, 3 = c)). Then it looks which number was chosen and then the corresponding letter is searched and written into the txt document until it has as many characters as you said at the beginning.

That would look like that:

@echo off

:main
cls
set /p anz=How many characters?: 
goto rand
:rand
set /a letter=%random% %%3
goto test

:test
if %letter%==1 goto 1
if %letter%==2 goto 2
if %letter%==3 goto 3

:1
if %anz%==0 goto finish
set /p print=a
set /a anz-=1
goto printin

:2
if %anz%==0 goto finish
set /p print=b
set /a anz-=1
goto printin

:3
if %anz%==0 goto finish
set /p print=c
set /a anz-=1
goto printin

:printin
echo %print% > Your_Password.txt                   <--- Here does the letter get written in the .txt file
goto rand

:finish
echo finish
goto main

But it only writes the last letter in the .txt file

For the beginning i have only made it with a, b, c in future i want to add the entire Alphabet

I am quite new in batch and collecting first my first experiences

CodePudding user response:

enter code here@echo o enter code heresetlocal enabledelayedexpansion enter code hereset Counter=1 enter code herefor /f %%x in (D:\COMP_T.txt) do ( enter code here` set "comp!Counter!=%%x" set /a Counter =1 )

CodePudding user response:

Better to first collect all needed characters in a variable and write to the file just once:

@echo off
setlocal enableextensions enabledelayedexpansion
REM valid chars for password:
set "chars=abcdefghijklmnopqrstuvwxyz"
REM number of chars:
set "CharCount=26"
REM clear pwd: 
set "pwd="
set /p "anz=How many characters?: "
REM %anz% times, add a random char:
for /l %%i in (1,1,%anz%) do call :addChar
(echo %pwd%)>"YourPassword.txt"
goto :eof

:addChar
rem get a random number [0..anz-1]
set /a rnd=%random% %% %CharCount%
REM add the rnd-th character from validChars to the pwd (zerobased count):
set "pwd=%pwd%!chars:~%rnd%,1!"
goto :eof

See set /? for how the random character is selected and for /? to learn how it does it anz times.
Also read about delayed expansion for why ! is used.

  • Related