Create a database within a bat file - variables

I am trying to create a bat file that is in essence a database. I want to be able to enter information that is tied to a single record. When I enter a record, I want to be able to look up the record by the card number assigned to it. The code I have now doesn't really work due to the fact that the variables are not being stored properly.
This is my code:
Color 5F
#echo off
:start
cls
echo ==========================================
echo Gift Card
echo ==========================================
echo.
echo What would you like to do?
echo.
echo 1 Add Card
echo 2 Check Information
echo 3 Edit Card Balance
echo 4 Delete Card
echo.
set /p choice=Please enter choice:
if /I %choice%==1 goto 1
if /I %choice%==2 goto 2
:1
echo.
set /p var=Enter Card Number:
set /p val=Enter Amount:
set /p fname=Enter First Name:
set /p lname=Enter Last Name:
set /p cbal=Enter Current Balance:
set /p diss=Enter Date issued:
#echo set %var%=%val%=%fname%=%lname%=%cbal%=%diss% > %var%.bat
echo.
echo The data has been stored!
pause
goto start
:2
echo.
set /p var=Please enter card number:
setlocal enabledelayedexpansion
call %var%.bat
echo !%fname%! !%lname%!'s !%var%! card has $!%cbal%! on it as of !%diss%!!
pause > nul
goto start
I have tried to send the variables separately and altogether and none have worked. I am thinking it is because I do not have the delayed expansion sytax correct.
Any help is very appreciated!

Your problem seems to lie where you generate the batch file to fill the variables... You generate only one line, which does not actually assign anything to any of the variables you need.
Try changing
#echo set %var%=%val%=%fname%=%lname%=%cbal%=%diss% > %var%.bat
to be
#echo set var=%var% > %var%.bat
#echo set val=%val% >> %var%.bat
#echo set fname=%fname% >> %var%.bat
#echo set lname=%lname% >> %var%.bat
#echo set cbal=%cbal% >> %var%.bat
#echo set diss=%diss% >> %var%.bat
This should allow your variables to be loaded back properly.
Also, change
echo !%fname%! !%lname%!'s !%var%! card has $!%cbal%! on it as of !%diss%!!
to read
echo %fname% %lname%'s %var% card has $%cbal% on it as of %diss%!
You should never use both ! and % to surround variables in a batch file, only one or the other. % should be used in most cases; ! should be used when you need to read a variable inside a multi-line "code block" (for example, the result of an if statement or the body of a for loop) which is surrounded by parentheses.
Some more advice:
You can put setlocal delayedexpansion just once in the beginning of the file, right after #echo off. However, you are not doing anything in this program (yet, at least) to need delayed expansion. Delayed expansion is used to enable accessing variables with the ! symbol and is only useful inside multi-line statement bodies surrounded by parentheses. Because of that, you should get rid of it completely unless/until you actually need it, as it can cause other problems.
There is no need for the "#" symbol in any command after you call #echo off (but it won't break anything). The # symbol simply suppresses echoing of the command which it precedes, but it is redundant because all commands are silenced by default after you call echo off. For this reason, it is important to only use it on the first line when calling #echo off, so that the user does not see that command echoed.

Related

Batch RPG Game with Login Function

I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.
title Lost Mine of Phandelvor
#echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=
if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame
:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces
:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES
:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create
:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES
:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start
:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=
if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start
:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create
:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman
:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter
:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main
:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit
I expect it to create the batch file after creating an account so that you can log in later.
For your menus, I would like to introduce you to choice.exe as an alternative to Set /P. It is far better to use it when input must be any one of a small set of known values. Set /P allows the end user to enter nothing or anything, and in order to maintain control you need to build in some input verification mechanism. To find out how choice.exe works, open a cmd.exe window and enter choice /? at the prompt.
Here is a rewritten example snippet of your script, (lines 1-43) to hopefully explain why:
#Echo Off
Title Lost Mine of Phandelvor
:EnterGame
ClS
Echo(
Echo Welcome to Lost Mine of Phandelvor
Echo ----------------------------------
Echo(
Echo 1. Create Account
Echo 2. Login
Echo 3. Exit
Echo(
Choice /C 123
If ErrorLevel 3 Exit /B
If ErrorLevel 2 GoTo Login
:CreateUser
ClS
Echo(
Set "username1="
Set /P "username1=What would you like your Username to be? "
If Not Defined username1 GoTo CreateUser
:CheckForSpaces
If Not "%username1: =%"=="%username1%" (
Echo Sorry you can not use spaces in your Username.
Choice /M "Is %username1: =%" okay"
If ErrorLevel 2 GoTo CreateUser
)
If Exist "%username1%.bat" GoTo :Login
Echo(
Set "password1="
Set /P "password1=What would you like your Password to be? "
However, before you continue with your script, based upon what I said about using Set /P. The end user can currently enter anything they want as username1. We've already checked for no entry and for spaces, but you're also saving the name as a filename too, %name%.bat. Along with the decimal character codes 0 through 31, Windows filenames cannot contain any of the following characters, \/:*?"<>|, so you'd need to incorporate further verification of username1. This verification procedure would need to be implemented before line 31 of the code above.
Before you do so however, you may want to consider changing your methodology and not saving the Username to the name of a file. The reason for this is that you'd also be wise not to use filenames ending with a ., or any named CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 either. So you would further need to include those verification checks of the input too.
Don't forget, you'll probably want to include a verification method for input entries to the %password1% prompt too!
Given the complexity involved with user input and Set /P you can see why I have recommended choice.exe as a control measure for your menus.
Ooh - so many errors!
First, add an extra line setlocal enabledelayedexpansion directly after the #echo off line. This has two effects - first, when your batch ends, your environment is restored to its original condition so that you don't get confused with variables that have been established by prior runs. second, it turns on delayed expansion mode - which is where the !variable! syntax you are using is activated, otherwise ! is simply an ordinary character.
Next, having accepted input from the ketboard with a set /p, you have no idea whether the user entered. In your validation if statements, use if "%var%"=="value" which overcomes most input problems.
Next, the syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.
And a little tip for games that need a save/restore feature:
If you reserve a character as a prefix for variables-you-want-to-save (eg all variables I want to save/reload start with #) then all you need to save a game is
set #>"mygamefile.txt"
and all you need to reload a game is
for /f "usebackqdelims=" %%a in ("mygamefile.txt") do set "%%a"
To zap all # variables (useful before reloading a game) use
for /f "delims==" %%a in ('set # 2^>nul') do set "%%a="
You should look at the thousands of code examples here on SO to find out how to use subroutines - you appear to be using "spaghetti code".
This code may help with your password-checking:
for /f "tokens=1,2" %%a in (passwordfilename) do if "%%a"=="%playername%" set "playerpass=%%b"
if "%playerpass%"=="%enteredpass%" goto gameon
This uses a single password file of the form
player1 password1
player2 password2
If player1 changes password, then append the new data to the file like this:
player1 password1
player2 password2
player1 newpassword
and the above for /f construct will then set playerpass to the last occurrence of player1 found.
This should provide you with a start and obviate your need for a subsidiary batch file. You'll have enough on your plate implementing these suggestions, but you should be able then to see the wood for the trees.
And implement changes one at a time, then test and debug them. Small steps will make the process a lot easier.
I'm using the same thing in my game. You need 2 functions, 1 to load and 1 to save. The save function should look something like this:
:: My save thing
:save
(
echo %var1%
echo %var2%
) > save.sav
and the loading portion should look something like this:
< save.sav (
set /p var1=
set /p var2=
)
also, one major recommendation, put all your scripts into separate files and folders. Like a normal game, example:
- MainGame
- Launcher.bat
- Resources
- Scripts
- Save.bat
- Load.bat
- Fight.bat
- Assets
- Title.txt
this is a similar structure to what I used in my game.

Set variable equal to a number in a text file Batch

I have a batch file (tickets.bat) and each time you create a different ticket, by setting multiple variables and echoing the variables to a text file, I want the ticket number to go up by 1. I tried to do this by creating a number.txt file and each time you go through the loop and create a new ticket, it sets %pnumber% to the text file, and then sets %number% to %pnumber% plus 1. But %pnumber% keeps setting to 0, even when the number.txt file contains the number 1 and doesn't change. This is what I have:
:start
cls
echo Enter Ticket Info Here:
set /p name="Name:"
echo Press Enter to Show Ticket Preview
set /a pnumber=C:\Batch\ticket\number.txt
set /a number=%pnumber%+1
echo %number% > "C:\Batch\ticket\number.txt"
echo %name% Ticket Number %number%
pause
goto start
It looks like my problem is that %pnumber% always sets to 0. Unless I'm missing something else. Basically, I need it to always increase %number% by 1, even if you close the Batch job and open it up again, so that's why I went to using a .txt file. Is it not seeing the number in the text file or something? It's one number on one line. Thank you.
Try Like this :
#echo Off
:start
cls
echo Enter Ticket Info Here:
set /p name="Name:"
echo Press Enter to Show Ticket Preview
set /p pnumber=<C:\Batch\ticket\number.txt
set /a number=%pnumber%+1
echo %number% >C:\Batch\ticket\number.txt
echo %name% Ticket Number %number%
pause
goto start

How to store variables within variables in Batch?

I am trying to store a concatenated set of variables into a newly SET variable. When I add a variable into another variable it doesn't seem to actually get set correctly. I'm curious if BATCH can store variables within variables, or if I have to do formatting beyond what I currently have:
Example: The 'oldDirectory' variable should display the same thing as "%progdata%\%datetime%"
#echo off
For /f "tokens=2-4 delims=/ " %%a in ("%DATE%") do (
SET YYYY=%%c
SET MM=%%a
SET DD=%%b
)
For /f "tokens=1-3 delims=/:." %%a in ("%TIME%") do (
SET HH24=%%a
SET MI=%%b
SET SS=%%c
)
SET datetime=%YYYY%%MM%%DD%_%HH24%%MI%%SS%
SET progdata=C:\ProgramData
#echo on
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="%progdata%\%datetime%"
echo %oldDirectory%
)
pause
try with :
CALL SET oldDirectory="%progdata%\%datetime%"
CALL ECHO %oldDirectory%
First method:
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="%%progdata%%\%%datetime%%"
call echo %oldDirectory%
)
Second method:
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="!progdata!\!datetime!"
setlocal EnableDelayedExpansion
echo %oldDirectory%
)
An interesting point is that echo %oldDirectory% command display the current value of progdata and datetime variables with the same value of oldDirectory!
EDIT: Example added
#echo off
set progdata=C:\ProgramData
echo First method:
SET oldDirectory="%%progdata%%\%%date:/=%%_%%time::=%%"
call echo %oldDirectory%
echo Second method:
SET oldDirectory="!progdata!\!date:/=!_!time::=!"
setlocal EnableDelayedExpansion
echo %oldDirectory%
Output:
First method:
"C:\ProgramData\14082013_211303.20"
Second method:
"C:\ProgramData\14082013_211303.21"
You have a standard DELAYED EXPANSION problem, discussed endlessly on SO.
When batch encounters a "Block statement" - that is typically a parenthesised statement spread over many lines such as your IF EXIST then the entire statement is parsed through to the closing parenthesis AND at this time, ANY %var% is replaced by the value of that variable as it stands WHEN THE STATEMENT IS PARSED
Consequently, your ECHO %olddirectory% is replaced by ECHO since olddirectory has no value AT PARSE TIME and executing ECHO will report ECHO is On/Off progdata on the other hand IS set at parse-time and hence echo Found %progdata% is replaced by echo Found C:\ProgramData
The very simplest cure is to move the ECHO statement outside of the block
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="%progdata%\%datetime%"
)
echo Olddirectory=%oldDirectory%
(I added the olddirectory= so that the echo statement finds something to echo if olddirectory is not set)
The second easiest way to display the value is
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="%progdata%\%datetime%"
CALL echo %%oldDirectory%%
)
Here, the ECHO command is not expanded in the context of the IF, but in the context of the CALL which acquires its environment from the run-time value of the IF context.
The third easiest way to display the value is by using the delayedexpansion option of a setlocal command. An NT batch command traditionally starts
#echo off
setlocal
which suppresses echoing and establishes a local environment. Any changes to the local environment are backed out when an endlocal or end-of-file is reached in the setlocal's context. If this mantra is consistently followed, we don't get the situation where a variable is established by one batch and the environment is 'dirty' for the next. Consider running your original twice within the same cmd session. progdata, and all of the other variables you are establishing would remain set for the second coming - and hence olddirectory may be set by your first invocation, and retain that stale data if for some reason it's not EXPLICITLY set in the second. setlocal backs all those changes out for you.
setlocal enabledelayedexpansion adds an extra facility to the mix. Whereas %var% is resolved to the PARSE-TIME value of var, if delayedexpansion has been invoked then !var! is resolved to the RUN-TIME value - as it changes in a FOR loop...
Hence, adding
SETLOCAL ENABLEDELAYEDEXPANSION
at a strategic point (after the #echo off until you're off your training wheels...) would allow you to make a simple change to the display of olddirectory
IF EXIST "%progdata%" (
echo Found %progdata%
SET oldDirectory="%progdata%\%datetime%"
echo !oldDirectory!
)

Variables in loops Dont Work, Batch

This is the new Script and it Still Doesn't Work
I Get The syntax of the command is incorrect.
on FOR /F "USEBACKQ tokens=*" %%A IN (TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command") DO (
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "C:\Windows\System32\tasks\at%num%" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command"`) DO (
set var=%%A
ECHO %var%
SET /a num=%num%+1
PAUSE
)
GOTO:START
To understand your code, I'm going to break it down into logic first then try to solve it. Let me know if I miss a detail...
Set num var to 0
Begin :Loop
set num var to its current value ::NOT NEEDED - You've specified this prior to the GOTO
increment num var by +1
if myfolder\at* file exists then read at%num% and find a string then output that line to %tmp%\1.txt ::Need quotations on file location.
set F var to the line stored in %tmp%\1.txt
set F="%%F: =%%" ::Please explain what you are trying to do with this command.
set F to start on 10th character and remove the last 11 characters from the line.
echo the variable
If it doesn't exist, exit, but if it does return to :Loop
You should tell us what you are attempting. If it is as simple as saving a variable from a text file output, set F=<file.txt will work. If it didn't, then something happened prior to that command. Still... what is set F="%%F: =%%"?
Unless you are using a FOR loop variable, there is no need to use %% on each end of the variable.
If this were a FOR loop, it would look like this:
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "myFolder\at%num%.txt" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "myFolder\at%num%.txt" ^| FIND /i "string"`) DO (
PAUSE
SET var=%%A
ECHO !var!
PAUSE
SET var=!var: =!
ECHO !var!
PAUSE
SET var=!var:~10,-11!
ECHO !var!
PAUSE
SET /a num=!num!+1
ECHO !num!
PAUSE
)
GOTO:START
One good practice to check if commands are working, such as SET, insert an ECHO on the variable and a PAUSE right after each time you believe the variable should be changed. This will track what has changed on the variable so you can see if your command was correct and the changes were made.
I'd suggest using Batch's inbuilt function for loops, see here.
Conditionally perform a command for a range of numbers
Syntax
FOR /L %%parameter IN (start,step,end) DO command
Or maybe iterating over files in a folder would be better for what you are trying to do?
Loop through files (Recurse subfolders)
Syntax
FOR /R [[drive:]path] %%parameter IN (set) DO command
Or iterating over file contents?
Loop command: against a set of files - conditionally perform
a command against each item.
Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO command
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
This site has plenty of examples here which should point you in the right direction.
There are a few issues with your code, I've amended as follows to get the variable populated with the contents of the temp file.
set num=0
:Loop
set /a num=%num%+1
if exist "myFolder\at*" (
TYPE "myFolder\at%num%" | FINDSTR "\<Command\>" > "%temp%\1.txt"
set /P F=<"%TEMP%\1.txt"
Echo %F%
Pause
)
I don't know if this is the problem, but have you tried enabling:
setlocal enabledelayedexpansion
Then, inside the loop (or the IF(...)), you use !foo! to signify environment variables instead of %foo%.
See setlocal /? and set /? for more information.

Removing double quotes from variables in batch file creates problems with CMD environment

Can anybody help with effective and safe way of removing quotes from batch variables?
I have written a batch file which successfully imports a list of parameters %1, %2, %3 etc. and places them into named variables. Some of these parameters contain multiple words, and therefor are enclosed in double quotes.
> "Susie Jo" (%1)
> "Smith Barnes" (%2)
> "123 E. Main St." (%3)
These %variables are next placed in named variables:
> set FirstName=%1
> set LastName=%2
> set ShipAddr=%3
verification of variables is done by echo.
> echo.%FirstName%
> echo.%LastName%
> echo.%ShipAddr%
results display as
"Susie Jo"
"Smith Barnes"
"123 E. Main St."
I need to eliminate the included quotes on selected variables. For instance, FirstName and LastName are used elsewhere and must not include quotes.
In a test batch file I was successful at eliminating quotes using the ~tilde character in variables.
> set FirstName=%~1
> set LastName=%~2
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path
> C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
returns
> 'C:\Documents' is not recognized as an internal or external command....
So it would appear that the addition of the ~tilde character to the in-coming %1 %2...%n variables has caused some change. Possibly some environment variables have been altered?
I also tried clearing quotes from within variable with various attempts using the FOR command. That seems awkward and I have been unable to learn how to accomplish this by creating a list of variable to perform the task:
something like this:
for %%g in (%FirstName% %LastName%) do (
set %%g=%%~g
set %%h=%%~h
set FirstName=%%~g
set LastName=%%h
echo.%FirstName% %LastName%
)
I think I have two issues.
My 'short and sweet' idea of inserting ~tilde in the incoming %1 %2 variables (%~1, etc) seems to have affected some settings and altered how CMD navigates long pathnames.
I'm still in search of a clean and easy way to eliminate quotes from selected named variables.
Any help for those more experienced would be most appreciated. I'm at the end of my skills here... need some guidance please!
edit 12/26/2009 13:36 PST
entire batch file:
:: dataout.bat
:: revision 12/25/2009 add ~tilde to incoming %variables to eliminate embedded "quotation marks.
:: writes address list using command line parameters
:: writes data output list for QBooks IIF import
:: writes Merchant Order data for RUI
:: sample command line string for testing
:: listmail[firstname][lastname]["address string"]["city string"][state][zip][Order#][PurchDate][Regname]["FirstName LastName"][TransactionID][PaymentMethod][Total][ProductID][Qty][Price_Each][PackPrep] [Shipping] [CommissionPmt] [Invoice#]
:: example: dataout Bellewinkle Moose "123 Green Forest Way" "Vancouver" WA 98664 1004968 05/25/2009 "Bellewinkle Moose" "Olive Oyl" 101738 "On Account" 20.67 FK-1P 1 8.95 3.00 1.39 239
#echo off
cls
c:
cd\
cd documents and settings\administrator\my documents\txt\batchtest
echo processing %1 %2
:VARISET
:: Convert %n command line parameters to string variables
set ($FirstName)=%~1
set ($LastName)=%~2
set ($BillingAddress1)=%~3
set ($BillingCity)=%~4
set ($BillingState)=%~5
set ($BillingPostal)=%~6
set ($OrderNumber)=%~7
set ($Purch_Date)=%~8
set ($RegistrationName)=%~9
shift
set ($TransactionID)=%~9
shift
set ($PaymentMethod)=%~9
shift
set ($Total)=%~9
shift
set ($ProductIdentifier)=%~9
shift
set ($Quantity)=%~9
shift
set ($Price_Each)=%~9
shift
set ($Pack_Prep)=%~9
shift
set ($Shipping)=%~9
shift
set ($ServiceFee)=%~9
shift
set ($Discount)=%~9
shift
set ($Invoice)=%~9
shift
set ($UnitPrice)=%~9
set _ShipCombName=%($FirstName)% %($LastName)%
echo ship combo name is %_ShipCombName%
pause
:: write string varibables to logfile
echo FN %($FirstName)% LN %($LastName)% BA %($BillingAddress1)% %($BillingCity)% %($BillingState)% %($BillingPostal)% %($OrderNumber)% %($Purch_Date)% %($RegistrationName)% %($TransactionID)% %($PaymentMethod)% %($Total)% %($ProductIdentifier)% %($Quantity)% %($Price_Each)% %($Pack_Prep)% %($Shipping)% %($ServiceFee)% %($Discount)% %($Invoice)% %($UnitPrice)% %_ShipCombName% >> d_out_log.txt
:: Assign Account by Service Provider
IF /i %($PaymentMethod)%==Amazon Receivables SET _QBAcct=Amazon.com
:: 12-25-2009 added second Amazon pm't method for versatility
IF /i %($PaymentMethod)%==Amazon SET _QBAcct=Amazon.com
IF /i %($PaymentMethod)%==MAST SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==MasterCard SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==Visa SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==PayPal SET _QBAcct=PayPalPmts
IF /i %($PaymentMethod)%==On Account SET _QBAcct=%($RegistrationName)%
IF /i %($PaymentMethod)%==Mail SET _QBAcct=%($RegistrationName)%
IF /i %($PaymentMethod)%==AMER SET _QBAcct=Auth/Net
IF /i %($PaymentMethod)%==DISC SET _QBAcct=Auth/Net
:: Assign Rep designator based on QBAccount
IF /i %($PaymentMethod)%==Amazon Receivables SET _Rep=Amazon
:: 12-25-2009 added second Amazon pm't method for versatility
IF /i %($PaymentMethod)%==Amazon SET _Rep=Amazon
IF /i %($PaymentMethod)%==MAST SET _Rep=BlueZap
IF /i %($PaymentMethod)%==MasterCard SET _Rep=BlueZap
IF /i %($PaymentMethod)%==Visa SET _Rep=BlueZap
IF /i %($PaymentMethod)%==PayPal SET _Rep=BlueZap
IF /i %($PaymentMethod)%==On Account SET _Rep=R B
IF /i %($PaymentMethod)%==Mail SET _Rep=R B
IF /i %($PaymentMethod)%==AMER SET _Rep=BlueZap
IF /i %($PaymentMethod)%==DISC SET _Rep=BlueZap
:: check for duplicate address data
findstr /i /s "%_ShipCombName%" addrlist.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :ADDRWRITE
if errorlevel 0 goto :ADDRFOUND
:ADDRWRITE
echo %_ShipCombName% >> addrlist.txt
echo %($BillingAddress1)% >> addrlist.txt
echo %($BillingCity)% %($BillingState)% %($BillingPostal)% >> addrlist.txt
echo. >> addrlist.txt
echo Address File Written
:ADDRFOUND
echo selected rep is %_Rep%
echo selected account is: %_QBAcct%
pause
:: RUI OUT
:: write Merchant Order ID & RUI Order ID to RUI
:: check for duplicate RUI data in writeRUI.txt
cd..
cd RegKOut
find /i "%($OrderNumber)%" writeRUI.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :RUIWRITE
if errorlevel 0 goto :IIFWRITE
:RUIWRITE
echo %($Invoice)% %($OrderNumber)% >> writeRUI.txt
:: end write RUI
:: IIF OUT
:IIFWRITE
:: Check for duplicate invoice data in writeIIF.txt
find /i "%($OrderNumber)%" writeIIF.txt
echo errorlevel: %errorlevel%
if errorlevel 1 goto :HEADWRITE
if errorlevel 0 goto :LINEWRITE
:HEADWRITE
:: write Header, Ship/Handling, discount, Rep & commission data to QB IIF import file
echo %($OrderNumber)% %($Purch_Date)% Invoice %($TransactionID)% %_QBAcct% Accounts Receivable %($Total)% %_Rep% >> writeIIF.txt
echo H/P %($Pack_Prep)% 1 ? >> writeIIF.txt
echo SHP %($Shipping)% 1 ? >> writeIIF.txt
echo DISC %($Discount)% 1 ? >> writeIIF.txt
echo Comm %($ServiceFee)% 1 ? >> writeIIF.txt
:LINEWRITE
IF /i %($ProductIdentifier)% equ PH-1 goto WRITE_DEFA ELSE goto WRITE_DISC
echo %($ProductIdentifier)%
:WRITE_DISC
::writes discounted prices parsed from custom variable:
echo %($ProductIdentifier)% %($Price_Each)% %($Quantity)% ? >> writeIIF.txt
goto :EOF
:WRITE_DEFA
:writes default prices parsed from Product data
echo %($ProductIdentifier)% %($UnitPrice)% %($Quantity)% ? >> writeIIF.txt
goto :EOF
:: 3-second delay
:: TYPE NUL | CHOICE.COM /N /CY /TY,3 >NUL
:EOF
You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).
Input:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget
Output:
widget="a very useful item"
widget=a very useful item
Note: To replace Double Quotes " with Single Quotes ' do the following:
set widget=%widget:"='%
Note: To replace the word "World" (not case sensitive) with BobB do the following:
set widget="Hello World!"
set widget=%widget:world=BobB%
set widget
Output:
widget="Hello BobB!"
As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):
#ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE
Output:
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .
%0 is the Script Name and Path.
%1 is the first command line argument, and so on.
Your conclusion (1) sounds wrong. There must be some other factor at play.
The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.
E.g.:
set cmd=%~1
set params=%~2 %~3
"%cmd%" %params%
Note the quotes around %cmd%. Without them, path with spaces won't work.
If you could post your entire batch code, maybe more specific answer could be made.
I usually just remove all quotes from my variables with:
set var=%var:"=%
And then apply them again wherever I need them e.g.:
echo "%var%"
Spent a lot of time trying to do this in a simple way.
After looking at FOR loop carefully, I realized I can do this with just one line of code:
FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I
Example:
#ECHO OFF
SET Quoted="Test string"
FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I
ECHO %Quoted%
ECHO %Unquoted%
Output:
"Test string"
Test string
The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1
Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to
specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
#SET SomeFileName="Some Quoted file name"
#echo %SomeFileName% %SomeFileName:~1,-1%
If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
#SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
I learned from this link, if you are using XP or greater that this will simply work by itself:
SET params = %~1
I could not get any of the other solutions here to work on Windows 7.
To iterate over them, I did this:
FOR %%A IN (%params%) DO (
ECHO %%A
)
Note: You will only get double quotes if you pass in arguments separated by a space typically.
This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.
All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
set widget="a very useful item"
set widget
widget="a very useful item"
set widget=%widget:"=%"
set widget
set widget=a very useful item"
The trailing quote " in line 4 is adding a quote " to the string. It should be removed.
The syntax for line 4 ends with %
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path
C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
returns
'C:\Documents' is not recognized as an internal or external command....
There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass
and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
as parameters to the
"C:\Documents"
program.
You need to quote it to run a batch file with spaces in the path:
> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"
would have worked.
#echo off
Setlocal enabledelayedexpansion
Set 1=%1
Set 1=!1:"=!
Echo !1!
Echo "!1!"
Set 1=
Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.
Azure devops sometimes uses double quoting character (") to specify string. Powershell can use single quote character (') to specify string. Naturally I wanted to have a flexibility to be able to specify parameters however I wish, so same parameter can be used from both - command line - via batch file, and as a powershell script, as any parameter, including empty value.
Quote natural thinking is to write something like this:
build.bat:
#echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal
But like you can guess - this does not work out of box - if no arguments are provided to batch file so %* == empty string. args expands as no string, and next replacement notices that args is not set - and instead of replacing string - it would append extra "=' garbage to args parameter.
Solution to this was just to add extra space in first assignment.
build.bat:
#echo off
setlocal enabledelayedexpansion
set args=%*
set args=%args:"='%
echo powershell -executionpolicy bypass "%~dpn0.ps1" %args%
endlocal
After this character translation should be correct:
C:\test>build
powershell -executionpolicy bypass "C:\test.ps1"
C:\test>build aa
powershell -executionpolicy bypass "C:\test\build.ps1" aa
C:\test>build "aa"
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'
C:\test>build 'aa'
powershell -executionpolicy bypass "C:\test\build.ps1" 'aa'