I am currently writing a batch file to create, edit, and delete journal entries for an internship I'm currently working on, I don't seem to understand how to get my if/else statements to work, this is my first time using batch, most of the coding I have done has either been in Linux or Python, so maybe I'm just making a dumb mistake:
:edit
echo Welcome to the editing menu!
echo To edit a journal entry, enter the date of the journal below in a MM-DD-YYYY format! (I.E. 05-8-1982)
powershell sleep 3
set /p filename2=What is the date of the entry you are looking for?
echo Searching for file now...
powershell sleep 1
if EXIST "%filename2%.txt" G:\Batch\JournalEntries\*
(
start "%filename2%.txt"
)
ELSE (
ECHO not found
From this point, when I run the program and get to the editing menu, I am asked to enter a filename. I put it in and then a new cmd window opens with the filename I've entered, as it is unable to find the name I entered (This is done on purpose, I am testing whether it will give me the else error or not).
Your fixed code must look like:
:edit
echo Welcome to the editing menu!
echo To edit a journal entry, enter the date of the journal below in a MM-DD-YYYY format! (I.E. 05-8-1982)
timeout /T 3 >nul
set /p "filename2=What is the date of the entry you are looking for? "
echo Searching for file now...
timeout /T 1 >nul
if exist "%filename2%.txt" (
if exist "G:\Batch\JournalEntries\*" (
start "" "%filename2%.txt"
) else (
echo Did not found files matching pattern G:\Batch\JournalEntries\*!
)
) else (
echo Did not found files matching pattern %filename2%.txt!
)
pause
Just some notes:
There is a timeout command in batch: it is used to wait for a specified period. Alternative: ping.
Quote var and value when setting variables like set "var=value". Use the same format even if there are /a or /p options.
You seem to misunderstand the if command usage. At least one parenthesis should be in the same line as if; see the above code block for more details.
It is good not to write with upper-case in batch. It just makes noise as it is a case-insensitive language.
It seems you made a mistake quoting %filename2%.txt file quoting both filename and filename and extension. Since quotes aren't allowed as a file/foldername, I have removed and just double-quoted filename and extension.
For more information about the commands used, please type in cmd.exe:
echo /?
timeout /? explains its usage
ping /? alternative to timeout
if /? explains syntax and usage of if
start /?
Related
I'm trying to create a batch file to insert a string from a .txt file at a specific place inside a string in 225 batch files - i.e., inserted into one line in the file at a specific place - but this question concerns the inserting part, and not the loop part, so I've left out the latter in my code example. It's also currently just displaying the text on-screen; not actually writing it to files.
The target files are a bunch of launch .bat files used for running a game server cluster using a tool, so I will have to leave each of them with the same names as they start with (Start XXYY.bat). They contain something along these lines:
start /high ShooterGame\Binaries\Win64\ShooterGameServer.exe Ocean?ServerX=0?ServerY=0?AltSaveDirectoryName=0000?ServerAdminPassword=1234?MaxPlayers=50?ReservedPlayerSlots=25?QueryPort=50002?Port=5002?SeamlessIP=192.168.1.225?RCONEnabled=true?RCONPort=28450 -log -server -NoBattlEye
exit
Where the ServerX, ServerY, AltSaveDirectoryNamen and all three Port settings are unique to each server, so these will have to remain unchanged.
I need to add several more settings, from another .txt file in the final version, but for this example I will just put the additions (the word INSERT added after the ReservedPlayerSlots setting, while keeping each setting divided by question marks) directly into this script.
My code is actually doing exactly what I want it to, but unfortunately it doesn't stop at that point, and decides to append more text than I wanted; specifically, everything I add to the ECHO command which is not a variable name.
To clarify, I get the exact output that I want... Plus the unwanted addition of a bunch of question marks and the word INSERT, which apparently come from my ECHO command, but I just have no idea why they get re-added.
My knowledge of batch scripting is fairly limited, so there might well be something basic that I've overlooked.
I've tried replacing the question marks in the output (which are required to be questions marks in the final version) with normal letters instead, but it doesn't change the behaviour; they were still appended to the expected output, just like the question marks they replaced.
#ECHO OFF
SET FileNum=0000
REM I will have the code loop through 225 files (0000-1414) in the final version, but for test purposes I just set it to one single file number manually here.
SET FileName=Start %FileNum%.bat
REN "%FileName%" temp.txt
FOR /F "tokens=1,2,3,4,5,6,7,8,9,10,11,12 delims=?" %%a IN (temp.txt) DO (
ECHO %%a?%%b?%%c?%%d?%%e?%%f?%%g?INSERT?%%h?%%i?%%j?%%k?%%l
)
REN temp.txt "%FileName%"
I expect this code to output this:
start /high ShooterGame\Binaries\Win64\ShooterGameServer.exe Ocean?ServerX=0?ServerY=0?AltSaveDirectoryName=0000?ServerAdminPassword=1234?MaxPlayers=50?ReservedPlayerSlots=25?INSERT?QueryPort=50002?Port=5002?SeamlessIP=192.168.1.225?RCONEnabled=true?RCONPort=28450 -log -server -NoBattlEye
exit
But what I am getting is this:
start /high ShooterGame\Binaries\Win64\ShooterGameServer.exe Ocean?ServerX=0?ServerY=0?AltSaveDirectoryName=0000?ServerAdminPassword=1234?MaxPlayers=50?ReservedPlayerSlots=25?INSERT?QueryPort=50002?Port=5002?SeamlessIP=192.168.1.225?RCONEnabled=true?RCONPort=28450 -log -server -NoBattlEye
exit???????INSERT?????
Which is the expected output, but with the unexpected re-addition of every symbol in the ECHO command which did not designate a variable at the end of the output (in this case ???????INSERT?????), just after the exit.
I'm stumped... I hope someone has an idea what I'm doing wrong here.
Okay, I applied the idea that aschipfl provided, and it seems to work now.
The IF NOT "%%b"=="" line seems to have done the trick, after I added the final line with the exit using another ECHO. My full script (including loop and write to file) is now like this:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET "Insert=SettingOne=True?SettingTwo=False?SettingThree=1.000000"
FOR /l %%x IN (0, 1, 14) DO (
FOR /l %%y IN (0, 1, 14) DO (
IF %%x LSS 10 (SET XNum=0%%x) ELSE (SET XNum=%%x)
IF %%y LSS 10 (SET YNum=0%%y) ELSE (SET Ynum=%%y)
SET "FileNum=!XNum!!YNum!"
SET "FileName=Start !FileNum!.bat"
ECHO Filename: !FileName!
REN "!FileName!" temp.txt
(
FOR /F "tokens=1-12 delims=?" %%a IN (temp.txt) DO (
IF NOT "%%b"=="" (
ECHO %%a?%%b?%%c?%%d?%%e?%%f?%%g?%Insert%?%%h?%%i?%%j?%%k?%%l
ECHO exit
)
)
) >edited.txt
REN edited.txt "!FileName!"
DEL /q temp.txt
ECHO has been updated
)
)
This is now working exactly as intended.
It's quite possible that there is a more elegant way of doing this, and I am cartain that there is a way of making this more general and less hard-coded, but it's good enough for my purposes.
I thank you for your help!
I have this assignment from my teacher in regards to creating a batch file that does something. its pretty huge assignment, but one part i stuck. it asks:
If the value of the userdomain variable is equal to the value of the computername variable then
Store into a file called output.txt the following information:
1. The current username
2. The current computername
So im thinking, my username(domain username) would never be same as a computer name anywhere in the world! lol
So that would NEVER happen! in this case i should do nothing!
So im confused. What am i missing?!
It is possible to give the computer the name of the user account in a domain. That is not forbidden. That your computer has a different name than your user account in domain or locally does not mean it is not possible.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
:RunNameCompare
if /I "%COMPUTERNAME%" == "%USERNAME%" (
setlocal EnableDelayedExpansion
echo User name: !USERNAME!>output.txt
echo Computer name: !COMPUTERNAME!>>output.txt
endlocal
) else (
echo/
echo Computer name and user account name are different.
echo/
%SystemRoot%\System32\choice.exe /N /M "Simulate identical names [Y/N]: "
if not errorlevel 2 set "COMPUTERNAME=%USERNAME%" & goto RunNameCompare
)
endlocal
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
See also the following pages and articles:
Wikipedia article about Windows Environment Variables
Microsoft article about Using Command Redirection Operators
Microsoft article about Testing for a Specific Error Level in Batch Files
Single line with multiple commands using Windows batch file
This answer for details about the commands SETLOCAL and ENDLOCAL
DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
The outer SETLOCAL and ENDLOCAL are used to create a local environment on running this batch file so that even after taking the simulate identical names option, the predefined environment variable COMPUTERNAME has its original value after running the batch file from within a command prompt window as recommended on debugging and verifying a batch file in development.
The inner SETLOCAL and ENDLOCAL are used to be able to output correct into file output.txt even computer and user account names containing command line critical characters like &()[]{}^=;!'+,`~|<> or ending with a space and a number in range 1 to 9 without enclosing both names in double quotes.
I have been writing some batch files now-a-days. I am beginner !. So i have made a custom batch in which by entering a setup name it launches it but. I'am having some problem creating this custom file.
#echo off
set /p lnk="Setup Name = "
if "%lnk%"=="install.itunes.x64.windows" goto itunes
:itunes
start=(path)(setup.exe).....
cls
But if a user enters "itues or "installitunes" or "KJEWBFciou" whatever that don't matchs my custom command I want a error Pop-up in this condition.
What can i Do?
and don't ask to put "if not "%lnk%" i have already tried help level:0
Because i have many setups like itunes if input will not equal to custom command it launches the next setup.
Please help me
Please igonre my errors i only made 'em here not in batch file.
in line 2 %lnk% , lnk
and line 3 "%lnk" ,"%lnk%"
Ok so..
1 #echo off
2 set /p %lnk%="Setup Name = "
3 if "%lnk%=="install.itunes.x64.windows" goto itunes
4 :itunes
5 start=(path)(setup.exe).....
6 cls
A few errors but you're close.
In line 2, you use:
set /p %lnk%=="Setup Name = " goto itunes
When setting a variable you can't use %% around it, but thats only used when comparing, because when creating the variable, the computer will replace [set /p %lnk%=] with [set /p =] which is invalid syntax.
In line 3:
if "%lnk%=="install.itunes.x64.windows" goto itunes
You never closed the quotes on the left of the '==' comparison. Do note you can also use [if %val1% equ %val2%] to the same results, which can help when you want to use other comparison tags.
A sidenote for the task you have set, although [goto itunes] works fine, its a good habit to use [goto :itunes] instead, and if you want to keep your code all together, you can just make a code block like:
if %val1% equ %val2% (
rem do stuff here
)
do note, if you either want a task to run if variables match, and if not try the next match, you can use multiple of these. Otherwise you can use:
if %val1% equ %val2% (
rem do stuff here
) else (
rem do other stuff here
)
In response to your issue on it launching the next command, thats because in line 3, you check if the variable matches your string, but if it doesnt batch skips it and runs the next line, which is your :itunes label.
All in all, this should work better, after you fix [start=(path)(setup.exe).....] to launch as desired.
#echo off && color f0 && title Itunes
:top
cls
set /p lnk="Setup Name = "
if "%lnk%"=="install.itunes.x64.windows" (
start=(path)(setup.exe).....
cls
)
cls
echo "%lnk%" was not matched to any choices...
pause
goto :top
:: _Arescet
I'm really new in this forum so I hope to respect all your rules, if not please forgive me!
I've just started studying something about batch files and I'm trying to execute a simple program from batch passing a parameter (the last aim is to submit a SAS program passing a date parameter).
Is it possible to activate a sort of list where I can choose some between pre-defined parameters?
--> This is the real aim of my work
I'm trying to "play" with this code:
#echo off
title Setting up execution period
echo Insert your date in the format GGMMMAAAA (es: '31DEC2003'D).
SET /p data_par=Insert the date to filter datas:
SET first_byte=%data_par:~1,1%
if "%first_byte%"=="" (
GOTO tag1
) else (
GOTO tag2
)
:tag1
msg * Missing value
:tag2
msg * Well done!
pause
I've tried in a lot of ways but it looks like the IF statement is not executed, I don't know where am I wrong.
Another question: why the prompt closes after i press "Enter" (afte the set/p command is executed)?
--> this has been resolved putting the "pause" command at the end of the script.
Thank you all for the attention,
Best regards!
Squotty
Put a pause at the end of your code to see the errormessages.
correct syntax for if when using else is:
if "a"=="b" (dosomething) else (dosemethingelse)
You can write it in several lines, but there are rules, where to set the paratheses:
if "a"=="b" (
echo this is code for something
rem more lines possible
) else (
echo this is code for something else
rem more lines possible
)
The first ( has to be on the same line than if.
) else ( have to be on one line.
If you press just enter with set /p, the variable remains unchanged (propably empty), so your code will go on with the code and hits the line else. Here it will tell you "else is not recognized as a command..."
at your tagx you should tell batch, where to stop execution. Use goto :eof to stop execution or goto somewhere to continue somewhere else. If you don't, it will just continue with the next lines.
Example:
:tag1
msg * Missing value
goto :eof
:tag2
msg * Well done!
goto :continue
pause
:continue
REM go on with the program...
(note: the pause will never be reached. I let it there to show you, how things work)
EDIT instead of just checking for some input you can check for the correct format:
echo %data_par%|findstr /r "[0-3][0-9][A-Z][A-Z][A-Z][1-2]0[0-9][0-9]">nul && (
echo correct format
goto continue
) || (
echo wrong format
goto startover
)
It's not bullet proof (eg. 38ABC2019 would be considered "correct"), but at least it checks for the correct format (e.g. 15.12.2019 or 12/15/2014 would be "not correct")
#ECHO OFF
SETLOCAL
SET "item1=date1"
SET "item2=date2"
SET "item3=date3"
SET "item4=date4"
FOR /l %%a IN (1,1,4) DO CALL ECHO(%%a. %%item%%a%%
ECHO(U. User-specified
choice /c 1234u
CALL SET selection=%%item%errorlevel%%%
IF NOT DEFINED selection (
SET /p selection="Your date-selection ? "
)
IF NOT DEFINED selection ECHO No selection made&GOTO :EOF
ECHO selection is %selection%
GOTO :EOF
This code may be of assistance.
It's normal to develop batch code using a batch window. Simply set up a shortcut to command prompt (Start>Programs>Accessories) which would allow you to run the script over and over and retain the results on-screen without using 'pause'. Editing can be accomplished by using notepad batchfilename.bat from the prompt (if you are using notepad for an editor - if using something better, then substitute that program's name). You can exit from the batch window by executing an exit command.
You can also get help on batch commands by using commandname /? - it's often cryptic and there are plenty of quirks. Extensive help available here on SO.
Bit of a tricky one. How can I correctly escape the following in a batch file?
echo /? display this help text
This particular combination of characters is treated as an "ECHO /?" command:
C:\Batch>ECHO /? display this help text
Displays messages, or turns command-echoing on or off.
ECHO [ON | OFF]
ECHO [message]
Type ECHO without parameters to display the current echo setting.
It does not respond to caret (^) escaping, ie. I've tried ^/? /^? and ^/^?.
NB: As a workaround, I found that inserting other characters in between is enough to bypass the ECHO command line processor, eg:
echo ... /? display this help text
Still, this is not ideal and I wondered if there was a way to acheive the desired output, namely with /? at the start of the echoed message.
For escaping echo arguments exists many variants, like echo., echo:, echo=
But only echo( seems to be secure against any appended text.
These one fails, if files exists like echo, echo[, echo] or echo+
echo.
echo[
echo]
echo+
These one fails, if a file in the current directory exists named my.bat
echo\..\my.bat
echo:\..\my.bat
echo.\..\my.bat
These one fails independet of a file
echo/?
echo,/?
echo;/?
Only the echo( seems to be always safe against any content
For escaping echo arguments, you can use the alternative syntax echo.:
echo./?