Simple batch script random number generator - batch-file

I am new to using the %random% command in batch scripts and I am trying to create a batch script to randomly create a number between 0 and 3. I wrote the following but with every instance (everytime I double-click the BAT file) I get the same number '1'. This defeats the purpose. Which is based on this number copy over a selected video file so it is random.
echo off
set numb=" "
set /a numb=%random% / 10000
echo %numb% :only used for testing
pause :only used for testing
if %numb% LEQ 1 goto trailer
if %numb% EQU 2 goto dragon
if %numb% EQU 3 goto live
:dragon
echo Dragon
copy /Y "F:\Skyrim SSE\mod backup - files\Dragon flyby - BGS_Logo.bik" "D:\SteamLibrary\steamapps\common\Skyrim Special Edition\Data\Video\BGS_Logo.bik"
exit
:trailer
echo Trailer
copy /Y "F:\Skyrim SSE\mod backup - files\Official Trailer-BGS_Logo.bik" "D:\SteamLibrary\steamapps\common\Skyrim Special Edition\Data\Video\BGS_Logo.bik"
exit
:live
Echo Live
copy /Y "F:\Skyrim SSE\mod backup - files\Dragonborne-live-BGS_Logo.bik" "D:\SteamLibrary\steamapps\common\Skyrim Special Edition\Data\Video\BGS_Logo.bik"
exit
I want to keep this as simple as possible as this really doesn't need to be complicated. Please help

Here's an example of one way to do it:
#Echo Off
Set "_s=F:\Skyrim SSE\mod backup - files"
Set "_d=D:\SteamLibrary\steamapps\common\Skyrim Special Edition\Data\Video\BGS_Logo.bik"
Set/A "_r=%RANDOM%%%3"
>Nul Choice /C 012 /N /T 0 /D %_r%
If ErrorLevel 3 GoTo Dragon
If ErrorLevel 2 GoTo Trailer
If ErrorLevel 1 GoTo Live
GoTo :EOF
:Dragon
Echo(Dragon
Copy /Y "%_s%\Dragon flyby - BGS_Logo.bik" "%_d%"
GoTo EndIt
:Trailer
Echo(Trailer
Copy /Y "%_s%\Official Trailer-BGS_Logo.bik" "%_d%"
GoTo EndIt
:Live
Echo(Live
Copy /Y "%_s%\Dragonborne-live-BGS_Logo.bik" "%_d%"
:EndIt
GoTo :EOF
I used CHOICE for no real reason, I just preferred it to a series of IF's with comparison operators ,EQU, NEQ, LSS, LEQ, GTR, GEQ.

Related

batch file loops once again at the end with nothing in variable

having an issue with a batch file which i would use in front of vagrant provisioning (merging files into an install-script to perform installation depending on user input) which looks like this:
#echo off
copy %CD%\Vagrantfile_base %CD%\Vagrantfile
echo Vagrant Provisionierung
echo 1 - nodejs
echo 2 - Nginx
echo 3 - Qt
echo 4 - Git
echo 5 - gcc
echo a - Alle vorgenannte Software
set /p choice=Mittels Zahlen durch Komma getrennt angeben, was installiert werden soll (Bspw. 1,2,3):
for %%i in (%choice%) do (
if "%%i"=="1" call :nodejs_install
if "%%i"=="2" call :nginx_install
if "%%i"=="3" call :qt_install
if "%%i"=="4" call :git_install
if "%%i"=="5" call :gcc_install
if "%%i"=="a" call :all_install
)
:nodejs_install
copy /b %CD%\software.sh+%CD%\software\nodejs_install.sh software.sh
PAUSE
goto :EOF
:nginx_install
copy /b %CD%\software.sh+%CD%\software\nginx_install.sh software.sh
PAUSE
goto :EOF
:qt_install
copy /b %CD%\software.sh+%CD%\software\qt_install.sh software.sh
PAUSE
goto :EOF
:git_install
copy /b %CD%\software.sh+%CD%\software\git_install.sh software.sh
PAUSE
goto :EOF
:gcc_install
copy /b %CD%\software.sh+%CD%\software\gcc_install.sh software.sh
PAUSE
goto :EOF
:all_install
call :nodejs_install
call :nginx_install
call :qt_install
call :git_install
call :gcc_install
PAUSE
goto :EOF
PAUSE
So when i execute the script it always calls the nodejs_install at the end even if i didnt choose it and i dunno why.
When i add an echo for the i it is empty shown.
Searching for very long but didnt found anything.
Maybe someone has an answer and/or fix for this?
Batch does not have true subroutines; if you do not protect the entry point of a subroutine with a GOTO to get around it, it will "fall through" into the routine. You need a GOTO :EOF after the ) and before the :nodejs_install.

How can i copy selected text file using command "FOR" in batch file?

Hello guys as you read in topic how can i make a selected file to copy to another location.
Im using my own Lithuanian language in this, if some one find it hard to understand tell me ill translate it. Right now it only creates new file when i start " name.bat test.txt" its not full code since there is lots of copy paste of same thing any ideas since im realy bad at .bat files.
And i need to use command "FOR"
:DEKUPAZAS
echo Pasirinkote Dekupazo kursus
echo Bendrine informacija apie si bureli
echo.
type dekupazas.txt
echo.
set U=dekupazas.txt
echo Ar norite:
echo 1) Irasyti sia informacija i naujai sukurta faila?
echo 2) Grizti kitu bureliu pasirinkimu?
echo 3) Grizti prie srities pasirinkimo?
choice /C 123 /N /M "Iveskite savo pasirinkima(1,2 arba 3): "
if errorlevel 255 goto KLAIDA
if errorlevel 3 goto SRITIS
if errorlevel 2 goto KT
if errorlevel 1 goto IRASYMAS
goto PRADZIA
:IRASYMAS
echo Pasirinkote irasyti sia informacija i jusu sukurto pavadinimo faila
echo Failas bus perkeltas i aplanka Pasirinkimas
if exist Pasirinkimas rd /S /Q Pasirinkimas
md Pasirinkimas
for %%U in (U) do dir %%U >>%1
move %1 Pasirinkimas >nul
goto PAB
The FOR /F statement reads each line of the file then does a directory listing of it captured to the first parameter to the .bat script.
I also took the liberty of creating a variable for the new directory name so that it does not need to be hardcoded so many times. "Hardcode" is two, four-letter words.
echo Pasirinkote irasyti sia informacija i jusu sukurto pavadinimo faila
echo Failas bus perkeltas i aplanka Pasirinkimas
SET NEW_DIR=Pasirinkimas
if exist "%NEW_DIR%" (RMDIR /S /Q "%NEW_DIR%")
MKDIR "%NEW_DIR%"
for /F %%a in (%U%) DO (DIR "%%~a" >>"%~1")
move "%~1" "%NEW_DIR%" >nul
goto PAB

Redirecting CMD Commands To An EXE File

Basically I have created an choice batch that every so often I can archive the contents of my boot data since I change it quite often and it works absolutely perfect, however I face the problem that every time I compile the batch from .BAT to.EXE with Advanced BAT to EXE converter the command 'bcdedit' never works and says “Not recognised as an internal or external command, operable program or batch file.”
Now the first thing I did was to make sure if I had the environment variables directed on my hard drive and it seemed fine:
Path: %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Users\Support\DOCUME~1\MYFILE~1\Programs\SYSTEM~1\DISKEE~1\
It has all the variables needed to work perfectly plus a few external ones which is ok then I thought that maybe I should try to make it direct on my folder, by doing some research I found on another forum:
Setting or Modifying a System Wide Environment Variable In CMD.EXE
I made a separate .BAT and I called it and it seems it did create the separate variable:
C:\Users\???\Documents\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Users\Support\DOCUME~1\MYFILE~1\Programs\SYSTEM~1\DISKEE~1" /f
But It Still Didn't Work!
I read upon another form:
Syswow64 Redirection
The person solution was to use Create Process () to create a program that automatically redirects him to the folder using sysnative (System32) but I'm a total beginner at C#, CMD is my strongest area when it comes to coding.
Please please I beg of you to help me as soon as possible and if you do have an answer please state in the easiest way possible and why. Here's my script just in case:
:START
echo.
echo Call apath.bat
echo.
echo.
echo (E) - Start Process.
echo (C) - Launch Part 2 Of Process.
echo (N) - Load NoDrives Manager.
echo (D) - Display Currect Account and Computer Information
echo (X) - Exit EDIM.
echo.
echo NOTE - It will not work if not started with Admin Privillages.
echo.
:Choice
set/p Option=Please enter your option:
if '%Option%' == 'E' goto :Incognito
if '%Option%' == 'C' goto :Touch
if '%Option%' == 'N' goto :Manager
if '%Option%' == 'D' goto :Data
if '%Option%' == 'X' goto :Exit
echo.
echo.
echo Invalid Option - Please Reselect.
goto :Choice
:RetryE
Echo An Error was found!
set/p RetryE=Retry? Y/N:
if '%RetryE%' == 'Y' goto :Incognito
if '%RetryE%' == 'N' goto :Exit
:Incognito
Timeout 5
echo.
echo.
echo.
Echo Saving OriginalBCD...
bcdedit /export "Data/BCD/OriginalBCD"
IF %ERRORLEVEL% GTR 0 goto :RetryE
IF %ERRORLEVEL% LSS 0 goto :RetryE
Echo Checking presence of BCD...
IF NOT EXIST "Data/BCD/OriginalBCD" goto :RetryE
Echo Deleting Boot Entry...
bcdedit /delete {current}
IF %ERRORLEVEL% GTR 0 goto :RetryE
IF %ERRORLEVEL% LSS 0 goto :RetryE
Echo Saving EditedBCD...
bcdedit /export "Data/BCD/IncogBCD"
IF %ERRORLEVEL% GTR 0 goto :RetryE
IF %ERRORLEVEL% LSS 0 goto :RetryE
Echo Checking presence of BCD...
IF NOT EXIST "Data/BCD/IncogBCD" goto :RetryE
Echo Allowing User Control For Assigning System Reserved Partitions...
Echo -Commands-
Echo Diskpart
Echo List volume
Echo Select Volume "" (The one that has no Letter and remember number)
Echo Assign Letter=Z
Echo Select Volume "" (The one that has Letter E and remember number)
Echo Remove Letter=E (This is the new system reserved partition)
Echo Then exit Diskpart to finish Part 1.
Diskpart
Echo Ready To Restart!
Timeout 5
Shutdown /r /t 30
Goto :Start
:RetryC
set/p RetryE=Retry? Y/N:
if '%RetryC%' == 'Y' goto :Touch
if '%RetryC%' == 'N' goto :Exit
:Touch
echo.
echo.
echo.
Echo Loading NDM...
Echo NOTE - Store the password somewhere safe!!!
Start "" "Data/NDM.exe"
Echo Loading EditedBCD...
bcdedit /import "Data/BCD/IncogBCD"
IF %ERRORLEVEL% GTR 0 goto :RetryC
IF %ERRORLEVEL% LSS 0 goto :RetryC
Echo Process Complete!
Timeout 5
Echo Returning to menu...
goto :Start
:Manager
echo.
Echo NOTE - Store the password somewhere safe!!!
Start "" /WAIT "Data/ndm.exe"
Echo Returning to Menu...
goto :Start
:Data
echo.
echo.
echo.
echo Processing Data...
Systeminfo
diskpart /s "Data/discpart.txt"
Echo Returning to Menu...
goto :Start
:Exit
Exit
Thanks So Much!
bcdedit is on the path by default so unless you are reusing the PATH variable then the problem is in the batch compiler.
You can test this by using the plain batch file - and if it works then you know where the problem is.

Access Denied...?

#echo off
color 4
ping localhost 2.5 > nul
echo Welcome to the configuration menu.
echo Move AH1.exe and AH2.exe to your desktop.
echo This only works the first time
echo SO BE CAREFUL!
echo Would you like this to start on computer startup?
echo say "yes" or "no" below.
set /p option=Option:
IF %ERRORLEVEL% EQU no goto no
IF %ERRORLEVEL% EQU yes goto yes
:yes
echo Move AH1.bat and AH2.bat to desktop.
::Copies files to dekstop of current user *For Windows 7
xcopy "%systemdrive%\users\%username%\Desktop\AH1.bat" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
xcopy "%systemdrive%\users\%username%\Desktop\AH2.bat" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
echo Moved.
echo Press any key to close Anti Hacker Configuration.
pause > nul
exit
:no
echo No?The program will not take full effect then.
pause
exit
If you want to test,make 2 batch files on your desktop called AH1 and AH2
It says Access Denied....why??
No matter what you put into the option variable, it will always go to :yes.
I'm guessing you got mixed up with the choice command when you were making this because errorlevel doesn't contain the option you choose when you have the set command.
From the set documentation:
%ERRORLEVEL% - expands to the current ERRORLEVEL value
So, you might want to change if %errorlevel% equ no goto no to if %option% equ no goto no.
Also, what happens if you don't put either yes nor no. You need to account for these things by perhaps having a exit command after the second if statement.

I'm trying to make an auto-updating .bat program

So, how I have it done right now, is that it that it calls another bat file to update it, and then that batch file updates, and sets %ERRORLEVEL% to 1. At the start of the original program, it checks if errorlevel is 1, if yes, it goes to the main menu, but right now, it doesn't call the update file, it just goes to the menu. This is my code
Main program
IF %errorlevel% EQU 1 goto begin
call updater.bat
:begin
echo MENU
Updater
set=errorlevel 1
wget (updatelink here)
call mainprogram.bat
Right now, sometimes it works, sometimes it doesn't, which leads me to believe that some command is somehow increasing the errorlevel, but the only code before the errorlevel check is
#echo off
color 0f
cls
set currentver=v0.5.6
(check code)IF %errorlevel% EQU 1 goto begin
https://code.google.com/p/flashcart-helper/source/browse/trunk/0.6/FlashcartHelperRobocopy.bat
Here is what I have right now.
Don't play around with errorlevel. It's an internal variable. At the start of a batch, errorlevel will be 0 because all you've done is set a local variable. This will almost always ( never say never ) succeed. Also, if errorlevel is 1, and I'm reading this correctly you also seem to have an infinite loop? From what I understand of what you've said your batches are like this:
Main
#echo off
color 0f
cls
set currentver=v0.5.6
IF %errorlevel% EQU 1 goto begin
call updater.bat
:begin
echo MENU
Updater
set=errorlevel 1
wget (updatelink here)
call mainprogram.bat
As errorlevel get's overwritten each time you do anything you're asking for trouble. Change %errorlevel% to %error% and it should solve your problems. As it's a local environment variable it should also be passed between batch files. Just be careful not to use error elsewhere.
Here is a solution using Dropbox Public Folders and no wget. It uses PowerShell that in on Win7+ machines.
Update the below https://dl.dropboxusercontent.com/u/12345678/ url with your own.
It auto creates a .conf file for configuration.
Set __deploy_mode to 1 for the file on dropbox so the version file can be updated but the script not accidentally executed.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET time_start=%time%
SET time_choice_wait=20
SET script_ver=1.00
SET script_name=%~n0
SET server_url=https://dl.dropboxusercontent.com/u/12345678/
SET script_name_bat=%~dp0%script_name%.bat
SET script_name_cfg=%~dp0%script_name%.conf
SET script_name_latest_ver=%~dp0%script_name%.latest.ver
ECHO %script_name% v%script_ver%
ECHO %script_ver% > %script_name%.current.ver
IF NOT EXIST "%script_name_cfg%" CALL :SCRIPT_MISSING_CFG
FOR /f "delims=" %%x IN (%script_name%.conf) DO (SET "%%x")
IF %__deploy_mode% EQU 1 GOTO :EOF
IF %auto_update_compare% EQU 1 CALL :SCRIPT_COMPARE_VER
:SCRIPT_MAIN
REM =======================================
REM === EDIT BELOW THIS LINE ==
REM TODO Add main content
ECHO.
ECHO Waiting for content...
REM === EDIT ABOVE THIS LINE ==
REM =======================================
GOTO END
:SCRIPT_MISSING_CFG
ECHO Creating new %script_name%.conf file...
ECHO __deploy_mode=0 > "%script_name_cfg%"
ECHO repository_base_url=%server_url% >> "%script_name_cfg%"
ECHO auto_update_compare=1 >> "%script_name_cfg%"
ECHO auto_update_download=1 >> "%script_name_cfg%"
ECHO Update %script_name%.conf as needed, then save and close to continue.
ECHO Waiting for notepad to close...
NOTEPAD "%script_name_cfg%"
GOTO :EOF
:SCRIPT_COMPARE_VER
ECHO Please wait while script versions are compared...
Powershell -command "& { (New-Object Net.WebClient).DownloadFile('%server_url%%script_name%.current.ver', '%script_name_latest_ver%') }"
IF NOT EXIST "%script_name_latest_ver%" GOTO END
SET /p script_latest_ver= < "%script_name_latest_ver%"
IF %script_ver% EQU %script_latest_ver% CALL :SCRIPT_COMPARE_VER_SAME
IF %script_ver% NEQ %script_latest_ver% CALL :SCRIPT_COMPARE_VER_DIFF
GOTO :EOF
:SCRIPT_COMPARE_VER_SAME
ECHO Versions are both %script_name% v%script_ver%
GOTO :EOF
:SCRIPT_COMPARE_VER_DIFF
ECHO Current Version:%script_ver% ^| Server Version:%script_latest_ver%
IF %auto_update_download% EQU 1 GOTO SCRIPT_DOWNLOAD_SCRIPT
ECHO.
ECHO Would you like to download the latest %script_name% v%script_latest_ver%?
ECHO Defaulting to N in %time_choice_wait% seconds...
CHOICE /C YN /T %time_choice_wait% /D N
IF ERRORLEVEL 2 GOTO SCRIPT_DOWNLOAD_NOTHING
IF ERRORLEVEL 1 GOTO SCRIPT_DOWNLOAD_SCRIPT
IF ERRORLEVEL 0 GOTO SCRIPT_DOWNLOAD_NOTHING
:SCRIPT_DOWNLOAD_SCRIPT
ECHO Please wait while script downloads...
Powershell -command "& { (New-Object Net.WebClient).DownloadFile('%server_url%%script_name%.bat', '%script_name_bat%') }"
ECHO Script Updated to v%script_latest_ver%^^!
REM User must exit script. Current batch is stale.
GOTO :END
:SCRIPT_DOWNLOAD_NOTHING
GOTO :EOF
:END
SET time_end=%time%
ECHO.
ECHO Script started:%time_start%
ECHO Script ended :%time_end%
:END_AGAIN
pause
ECHO.
ECHO Please close this window
ECHO.
GOTO END_AGAIN
You can do that through these steps:
1.put two files in server,a config file, a higher version bat file which need to update; set last version num. in config file.
2.client bat should be checked update at every startup time. you can read the news version in server config file, then compared to local bat file version. if not equal, so do update, else other wise.
Do you have any problems?

Resources