Can't enter a variable in DOS - batch-file

I'm trying to run a batch file in vDOS (DOS emulator), where I want the user to input two variables. Every time I run the file, it doesn't let me enter the variables.
SET /P in=Input:
SET /P out=Output:
What I expected to happen was that It'd let me enter the input for the variables.
Instead, it executes both of the commands as they are (without letting me enter the input).

Windows cmd and MS-DOS are very different things and one of the differences is the set command. In MS-DOS the only form of set is set variable=value. There are neither set /A, set "variable=value" nor set /P.
set /P is a feature of Windows NT's cmd.exe. In DOS you must use 3rd party software to get user input and store in a variable. Here are some solutions
SENVAR.COM
SENVAR INPUT Input string:
EDITVAR and CHOOSE
editvar -p "Input string: " INPUT
FC.COM
#echo off
:: based on batch from PC Magazine June 27, 1995 page 248
:: this version puts temps in C:\DOS dir and shortens var names
:: User input is returned in variable STR
:input
> C:\DOS\en#er.bat fc con nul /lb1 /n|date|find " 1: "
> C:\DOS\enter.bat echo set str=
>>C:\DOS\enter.bat echo :loop
>>C:\DOS\enter.bat echo if not '%%str%%==' set str=%%str%% %%5
>>C:\DOS\enter.bat echo if '%%str%%==' set str=%%5
>>C:\DOS\enter.bat echo shift
>>C:\DOS\enter.bat echo if not '%%5==' goto loop
call en#er.bat
del C:\DOS\enter.bat
del C:\DOS\en#er.bat
ANSI.SYS
#ECHO OFF
REM * Ask for USeR INPUT and store it in variable USRINPUT
REM * Assumes ANSI.SYS is loaded
REM * Written by Rob van der Woude
SET USRINPUT=
REM * Turn on ANSI key translation (translate Enter
REM * key to F6+Enter sequence) and ask for input:
ECHO ←[13;0;64;13pEnter one word only . . .
REM * Copy entered text to temporary file:
COPY CON %TEMP%.\~USRINP.TMP
REM * Turn off ANSI key translation and clear irrelevant screen output:
ECHO ←[13;13p←[3A←[K←[1B←[K←[1B←[K←[2A
REM * Add empty line to temporary file. The empty line
REM * will be used to stop DATE asking for new date.
ECHO.>> %TEMP%.\~USRINP.TMP
ECHO.>> %TEMP%.\~USRINP.TMP
REM * Create a temporary batch file that will store the
REM * entered text into the environment variable USRINPUT:
TYPE %TEMP%.\~USRINP.TMP | DATE | FIND "):" > %TEMP%.\~USRINP.BAT
REM * Create more temporary batch files. Add
REM * more command line parameters if necessary,
REM * as in: ECHO SET USRINPUT=%%3 %%4 %%5 %%6 %%7 %%8 %%9>CURRENT.BAT
ECHO SET USRINPUT=%%3>CURRENT.BAT
REM * VOER.BAT and TYP.BAT are replacements for CURRENT.BAT for Dutch
REM * DOS versions; add your own language versions if necessary:
ECHO SET USRINPUT=%%6>VOER.BAT
ECHO SET USRINPUT=%%4>TYP.BAT
REM * This temporary batch file now sets the variable USRINPUT:
CALL %TEMP%.\~USRINP.BAT
REM * Display the result:
ECHO You typed: ←[1m%USRINPUT%←[0m
ECHO.
PAUSE
REM * Finally, clean up the mess of temporary files:
FOR %%A IN (%TEMP%.\~USRINP.BAT %TEMP%.\~USRINP.TMP VOER.BAT TYP.BAT CURRENT.BAT) DO DEL %%A
The ← is the escape character (27h)
In case you just want to get simple answers like Y/N then CHOICE.COM is designed for that purpose
See also
MS-DOS 6.22 Batch File User Input to Environment Variable
Prompt for variable in DOS 7.1

/P didn't get introduced until Windows 2000 or NT. Legacy MS-DOS or equivalent won't have it. https://www.computerhope.com/sethlp.htm

Related

Batch - Multiple file outputting with variable replace value

I'm trying to create a .bat program to replace two strings inside one text file and output the modified text multiple times.
So far so good...
The purpose of my program is to calculate the number of months between two dates (Ex: 01/2016 and 05/2017 will result in 17 months), and generate one configuration file for each month for a 3rd party program (17 output files in my example). This can be accomplished by replacing two tags ( and ) inside a template configuration file with the respective month/year values in that range.
My code so far is below:
#echo off &setlocal
setlocal ENABLEDELAYEDEXPANSION
cls
set "CNST_SEARCH_YEAR=<VAR_YEAR>"
set "CNST_SEARCH_MONTH=<VAR_MONTH>"
set "CNST_FILE_TEMPLATE=config_template.properties"
set "CNST_FILE_TMP=tmp_config.properties"
rem ===============================
rem INPUT DO USUÁRIO
rem ===============================
set "start_year=2014"
set "start_month=3"
set "end_year=2015"
set "end_month=7"
rem ===============================
rem DEFINIÇÂO DO TOTAL DE ITERAÇÕES
rem ===============================
set /a "iterations=(%end_year%*12 + %end_month%) - (%start_year%*12 + %start_month%) + 1"
echo DISPARO AUTOMATICO DA ROTINA AGENT - v1.0
echo ================================
echo Total de iteracoes: %iterations%
echo ================================
rem ===============================
rem EXECUÇÃO DO LOOP PRINCIPAL
rem ===============================
set v_year=%start_year%
set v_month=%start_month%
for /L %%i IN (1, 1, %iterations%) do (
echo ================================
echo Iteracao: %%i
echo !v_year! / !v_month!
echo Gerando parametrizacoes...
for /f "delims=" %%j in (%CNST_FILE_TEMPLATE%) do (
set "line=%%j"
set "line=!line:%CNST_SEARCH_YEAR%=!v_year!"
set "line=!line:%CNST_SEARCH_MONTH%=!v_month!"
echo !line! >> "%CNST_FILE_TMP%_%%i"
)
echo Executando Agent...
rem jre\bin\java.exe -jar gdc-agent-totvs-2.0.0.jar %CNST_FILE_TMP%
echo Apagando arquivo temporario...
rem del %CNST_FILE_TMP%
IF !v_month! EQU 12 (
set v_month=1
set /a v_year=!v_year!+1
) ELSE (
set /a v_month=!v_month!+1
)
echo ================================
)
endlocal
pause
My problem relies in the lines:
set "line=!line:%CNST_SEARCH_YEAR%=v_year!"
set "line=!line:%CNST_SEARCH_MONTH%=v_month!"
Because I can't use delayedExpansion multiple times inside that command. Also I can't define the v_year and v_month variables before the for loop, because their values are being set by the loop.
I'm using plain batch script since this program will be sent to other people who might not have powershell or other scripting tool.
Any ideas people?
Thanks.
Or combine the old fashioned call variant
call set "line=%%line:!CNST_SEARCH_YEAR!=!v_year!%%"
call set "line=%%line:!CNST_SEARCH_MONTH!=!v_month!%%"
To escape a percent sign from being interpreted as enclosing a variable you have to double it. The parser reduces the two %% to a single one in this step.
The normal delayed expansion for the !var! is executed.
The call forces a second evaluation of the parser which find this time the single percent signs and acts on current values.
To learn more on this topic read How does the Windows Command Interpreter (CMD.EXE) parse scripts?
You can try with something like
for %%v in (!v_year!) do set "line=!line:%CNST_SEARCH_YEAR%=%%v!"
This simply moves the delayed expanded value into a for replaceable parameter that can be used in the delayed expansion expression used in the set command

DOS echo %variable% "Echo is ON"

I have a dos batch file.
mycommand.exe>c:\temp
find /B Serv c:\temp>c:\temp2
set /p var1=<c:\temp2
SET var2=%var1:~-7%
echo %var2%
This is only DOS, not windows environment.
The problem is that, the batch file output is:
"Echo is ON". Can't echo the VAR2 variable.
mycommand.exe is a simple app. Not important.
> type c:\temp"
VERSION 45.2
TAG1 NUMBER is 1234567
Serv NUMBER is 9654754
> type c:\temp2
c:temp Serv NUMBER is 9654754
What can I do, If I would like echo the VAR2 variable?
I can't use "setlocal enabledelayedexpansion" because setlocal "Command or filename not recognized".
Edit: What am I want exactly?
I would like to ECHO mycommand.exe output 3rd line last 7 characthers. Thats all.
"good old DOS" is old, but not very good.
Your problem can be solved, basicly by building a temporary .bat file.
It's described in detail here:
https://support.microsoft.com/en-us/kb/66292
I have no DOS available, so I can't test, but this should work for you:
mycommand.exe>c:\temp.txt
find "Serv " c:\temp.txt>c:\temp2.txt
REM init.txt should already exist
REM to create it:
REM COPY CON INIT.TXT
REM SET VARIABLE=^Z
REM ( press Ctrl-Z to generate ^Z )
REM
REM also the file "temp2.txt" should exist.
copy init.txt+temp2.txt varset.bat
call varset.bat
for %%i in (%variable%) do set numb=%%i
echo Server number is: %numb%
REM just because I'm curious, does the following work? :
set var2=%variable%
echo var2 is now %var2%
The manual creation of init.txt has to be done once only, if you can live with, that it always creates a variable with the same name (therefore the last two lines, so you could use the same init.txt over and over again - please feedback, whether it works - I'm quite curious)

Is there anyway to have preset data for user input in a batch file?

So basically I have a batch file that requires alot of user input. I was wondering if it was possible to have any filler data already present when the question is asked, and if the user needs to change something, they can go edit that data. For example
And then the user enter their first and last name.
But is it possible to start with a default name that the user can go back and edit if they need?
This probably isn't necessary, But this is the code I use for the user input.
Set /p "Author=Please enter your name: "
And I understand for the Author it wouldn't make much sense to have preset data, but there are other instances where it would be useful for me to do this. Is it possible?
nearly impossible to edit a preset value with pure batch, but you can easily give a default value (works, because set /p is not touching the variable, if input is empty)
set "author=First Last"
set /p "author=Enter name or press [ENTER] for default [%author%]: "
echo %author%
The method below have the inconvenience that the screen must be cleared before the user enter the data, but I am working trying to solve this point:
EDIT: I fixed the detail of the first version
#if (#CodeSection == #Batch) #then
#echo off
rem Enter the prefill value
CScript //nologo //E:JScript "%~F0" "First Last"
rem Read the variable
echo -----------------------------------------------------------
set /P "Author=Please enter your name: "
echo Author=%Author%
goto :EOF
#end
WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0));
For further details, see this post.
You can set the var first and then prompt the user only if it's not defined like so:
set Author=First Last
if not defined Author set /p "Author=Please enter your name: "
You can also do this backwards where you can define a value if the user didn't define it, like so:
set /p "Author=Please enter your name: "
if not defined Author set Author=First Last
There Is another way yet to achieve this. It uses vbs script to get input and assign it to a variable, -The script can be created within and called from .bat files.
I developed this method as an alternative to accepting user input from set /p in order to validate input and prevent setting of variables with spaces or special characters.
*Validation methods omitted as does not relate to the question
Best method is to have the script generator as a secondary .bat file that you can call, as it allows for a lot of versatility regarding the information the vbs input box conveys, as well as being able to be used in any circumstance within one or more .bat files you want to be able to control input defaults with.
In your main program, when Preparing to get input-
REM Define title:
Set inputtitle=The title you want the input box to have
REM Declare variable to be assigned:
Set variableforinput=VariableName
REM Define the default Variable Value:
Set defaultinput=VariableName's Desired Default Value
REM getting the Input:
CALL "inputscript.bat" %inputtitle% %variableforinput% %defaultinput%
inputscript.bat:
#echo off
SET inputtitle=%~1
SET variableforinput=%~2
SET defaultinput=%~3
SET %variableforinput%=
SET input=
:main
REM exit and cleanup once variable is successfully defined
IF DEFINED input GOTO return
REM this creates then starts the VBS input box, storing input to a text file.
(
ECHO Dim objFSO 'File System Object
ECHO Set objFSO = CreateObject("Scripting.FileSystemObject"^)
ECHO Dim objTS 'Text Stream Object
ECHO Const ForWriting = 2
ECHO Set objTS = objFSO.OpenTextFile("%userprofile%\getinput.txt", ForWriting,
True^)
ECHO objTS.Write(InputBox("Please enter %variableforinput% to continue.","%inputtitle%","%defaultinput%",0,0^)^)
ECHO objTS.Close(^)
ECHO Set bjFSO = Nothing 'Destroy the object.
ECHO Set objTS = Nothing 'Destroy the object.
) >GetInput.vbs
START GetInput.vbs
REM a pause that allows time for the input to be entered and stored is required.
cls
ECHO (N)ext
CHOICE /T 20 /C nz /N /D n >nul
IF ERRORLEVEL ==2 GOTO main
IF ERRORLEVEL ==1 GOTO loadinput
:loadinput
IF NOT EXIST "%userprofile%\getinput.txt" GOTO invInput
<%userprofile%\getinput.txt (
SET /P input=
)
IF NOT DEFINED input GOTO invInput
REM opportunity for other validation of input before returning to main.
GOTO main
:invInput
SET input=
IF EXIST "GetInput.vbs" (
DEL /Q "GetInput.vbs"
)
REM ends the vbs script ready for the next attempt to provide input
taskkill /pid WScript.exe /T >nul
Timeout 1 >nul
GOTO main
REM assigns the input value to the variable name being set in Your Main program.
:return
SET %variableforinput%=%input%
SET input=
IF EXIST "%userprofile%\getinput.txt" (
DEL /Q "%userprofile%\getinput.txt"
)
IF EXIST "GetInput.vbs" (
DEL /Q "GetInput.vbs"
)
GOTO :EOF
I wrote an open-source Windows console program called editenv that replaces my older editv32/editv64/readline.exe utilities:
https://github.com/Bill-Stewart/editenv
Basically, editenv lets you interactively edit the value of an environment variable. One of my common use cases is to edit the Path environment variable for the current process:
editenv Path
editenv also provides the following convenience features:
--maskinput allows you to hide the typed input (note that this feature does not provide any encryption or security)
--allowedchars and --disallowchars allow you to specify which characters are allowed for input
--minlength and --maxlength let you choose a minimum and maximum length of the input string
--timeout lets you specify a timeout after which input is entered automatically
The most recent binaries are available here:
https://github.com/Bill-Stewart/editenv/releases
askingFile.cmd < response.txt
Take the input to the batch from the indicated file, one line per answer

creating a batch file to copy pictures to a network drive

How do I create a batch file that will copy files from a camera to a directory that is prompted from the command line?
example folder structure: {shared drive start folder} <year> <month> <(prompt user for name)> [delete pictures after copied]
I am looking to get this to work to copy pictures from various cameras to one shared folder and have it all sorted by year then month and finally by the user prompted name. I know very little command line commands, all the switches and %'s.. i get lost pretty quickly.
Windows 7 computers and most likely SD cards in readers because most of the cameras don't show up with drive letters (this is part of my problem)
The code:
Show errors:
ECHO ON
type of file:
SET type=jpg
to set where the files are going:
NET USE M:\public\am_class\
to get user input i would use "SET /P" so i would do:
SET /P SDdrive=Enter Sd Card drive letter:
Get month and year(and day in case its needed later) to create initial folders:
FOR /F "TOKENS=1* DELIMS= "%%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS= "%%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/ "%%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ "%%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
change dir to the correct location... this im not sure about but the "NET USE" gives me a direction to look in (figured out and placed correct code):
cd\
cd /DM:\public\am_class\"
make new folders in above main folder
mkdir "%yyyy%"
cd "%yyyy%"
mkdir "%mm%"
cd "%mm%"
!!next question is this correct to get it to create a folder from the user prompted info? (This is corrected and correct)
SET /P foldername=Please enter assignment number and press enter:
mkdir "%foldername%"
cd "%foldername%"
Go to SDdrive:
%SDdrive%
Find the Path of the files:
FOR /F "TOKENS=2 DELIMS\" %%A IN ('dir /b /s *.%type%') DO SET p1= %%A
Change folder and copy to "foldername" folder
CD"%p1%"
COPY *.* %foldername%
Delete the SDcard pics after complete:
Set /P delete=Delete SD card pictures (y/n)?
IF /I "%delete%"=="y" GOTO delY
IF /I "%delete%"=="y" GOTO delN
:delY
%SDdrive%
del /q *.*
explorer.exe \\landis.xxx\public\am_class\%foldername%\
:delN
explorer.exe \\landis.xxx\public\am_class\%foldername%\
Pause for testing only (will be removed in final version):
Pause
I hope that helps some.
Use the net use command to map the windows share to a drive like X:\ and then use
xcopy with some appropriate arguments to copy the files.
Like I said in my comment, your question is very broad with a lot of things to consider. I wrote a batch-file that I have used for years on many versions of Windows to download my pictures from SD cards. It does a good job, but it does not take into account that two different SD cards may have the same picture names on them -- even though they are different pictures. It simply skips pictures that have already been downloaded with the same filename in the destination folder.
I'm not going to write your code for you, nor do I have the time right now to help you navigate your way through learning the batch-file language, but I can at least post the two batch files that I use so that you can see some of the techniques that I used to accomplish what you're trying to do.
I created a shortcut in the SendTo folder that points to the DownloadPictures.bat so that when I insert an SD card into the card reader, I can send the images folder on the SD card to the shortcut and it downloads all of the pictures, separating them into folders based on the year/month/day they were taken. Then it opens each distinct destination folder using explorer.exe. The CMD window does not show anything during the download (i.e., nothing is echoed to the window), however, the title shows the overall progress and current image filesize (e.g., "1/300 7341254 bytes").
In order to grep the year, month and day from the file dates, I use another batch-file I wrote called SubStr.bat that lets me get a substring of the output of any DOS command and assign it to a variable. You must use Delayed Command Line Expansion for everything to work.
Please remember that this is not meant to be a solution for your question, but is simply an example that shows how to do some of what you are asking -- so that you can use it as a reference as you work on your own solution.
DownloadPictures.bat
#echo off
setlocal ENABLEDELAYEDEXPANSION
cd /d c:\
title Counting the files to download...
set _total=0
for /f "delims=" %%i in ('dir %1 /a-d /b /s') do set /a _total+=1
set _cnt=0
for /f "delims=" %%i in ('dir %1 /a-d /b /s') do (
set /a _cnt+=1
if /I "%%~xi" neq ".ctg" (
title !_cnt!/%_total%: %%i - %%~zi bytes
call substr "echo %%~ti" _date 0 n n "" sub 0 10
call substr "set _date" _year 0 n n "" end 4
call substr "set _date" _month 0 n n "" sub 6 2
call substr "set _date" _day 0 n n "" sub 9 2
set _dir=Q:\Photographs\Downloads\!_year!.!_month!.!_day!
md !_dir! > nul 2>&1
if not defined _old_dir set _old_dir=!_dir!
if "!_dir!" neq "!_old_dir!" (explorer !_dir!&set _old_dir=!_dir!)
if not exist !_dir!\%%~nxi copy %%i !_dir! > nul 2>&1
)
)
explorer !_dir!
echo All the pictures in directory %1 have been downloaded.
endlocal
SubStr.bat
#echo off
if "%7"=="" goto Help
:ExtractString
:: Remove the first and last " and convert all "" to ".
set __command_=%1
set __command_=%__command_:""="%
set __command_=%__command_:~0,-1%
set __command_=%__command_:~1%
:: Execute the command and direct the output to a unique file.
%__command_% > %TEMP%\_záfileáz_
:: Extract the specified line from the output file. (Note: You can't use 'skip'
:: with a value of '0'.) I used '«' as the delimiter because it is a character
:: that I will never encounter and this will ensure that I get the whole line
:: returned from the 'for' statement.
if "%3"=="0" (
for /f "delims=«" %%i in (%TEMP%\_záfileáz_) do if not defined _závaráz_ (set _závaráz_=%%i)
) else (
for /f "skip=%3 delims=«" %%i in (%TEMP%\_záfileáz_) do if not defined _závaráz_ (set _závaráz_=%%i)
)
if /i "%7"=="all" goto Finish
if /i "%7"=="sub" set _závaráz_=!_závaráz_:~%8,%9!
if /i "%7"=="end" set _závaráz_=!_závaráz_:~-%8!
:Finish
:: Kill spaces, quotes.
if /i "%4"=="y" set _závaráz_=%_závaráz_: =%
if /i "%5"=="y" set _závaráz_=%_závaráz_:"=%
:: Remove unwanted characters (pad the front with an unlikely string so that the
:: FOR statement will never complain because of an empty set). The %%~i notation
:: strips quotes out of the string and spaces are delimiters. This is why they
:: each (spaces and quotes) have their own parameters above...
set __remove_=%6
set __remove_=ßa¯¦¯aß %__remove_:~1%
set __remove_=%__remove_:~0,-1%
set __remove_=%__remove_:""="%
for %%i in (%__remove_%) do set _závaráz_=!_závaráz_:%%~i=!
:: Set the output variable.
set %2=!_závaráz_!
:Cleanup
set _závaráz_=
del %TEMP%\_záfileáz_
set __command_=
set __remove_=
goto TheEnd
:Help
echo.
echo SubStr
echo ================================================================================
echo.
echo Syntax:
echo.
echo SubStr ["command"] [output variable] [Lines to Skip] [Remove Spaces]
echo [Remove Quotes] [Remove Other] [action [var1] [var2]]
echo.
echo Parameters:
echo.
echo Command - The command that creates the output characters. If the
echo command includes calling another batch file, issue the
echo command by using the 'call' function
echo (e.g., "call another.bat"). When your command is passed,
echo it must be enclosed in quotes. If part of the command needs
echo to also have quotes (i.e., for long filenames), the strings
echo within the command that need to be quoted need to be double
echo quoted (e.g., "dir ""c:\win 2000\notepad.exe"" /x"). When
echo the command is executed, the initial and final quotes will
echo be stripped off and all sets of double quotes ("") will be
echo replaced with single quotes (").
echo.
echo Output Variable - The name of the variable to use (set var=copied text).
echo.
echo Lines to Skip - The number of lines before the line from which you want to
echo copy text.
echo.
echo Remove Spaces - Removes spaces out of the copied text.
echo.
echo Remove Quotes - Removes quotes from the copied text.
echo.
echo Remove Other - A string of strings that should be removed from the copied
echo text. The set of strings or characters must be enclosed in
echo a single set of double quotes. At times, some characters
echo may not be elimated (e.g., a comma) unless it too is
echo enclosed in quotes. To do this, the quotes must be doubled.
echo For example: "a b c d "","" e f h"
echo.
echo Action - Action to perform:
echo All - Copies entire string.
echo Sub - Extracts part of the string where var1 is the
echo starting position and var2 is the number of
echo characters to copy. var1 is zero based. A negative
echo value for var2 omits the specified number of
echo characters from the end of the string.
echo End - Only extracts the specified number of characters
echo from the end of the string (specified by var1).
echo.
echo Example:
echo.
echo SubStr "dir c:\windows\system32\notepad.exe /-c" _filesize 5 y n "" sub 20 18
echo.
echo This command assigns the size of notepad.exe to the variable _filesize.
echo Try running it and then type 'set _' at the command prompt.
echo.
echo Notes:
echo.
echo Make sure delayed command line expansion is enabled in the calling batch file
echo via the "setlocal ENABLEDELAYEDEXPANSION" command, or enable it globally by
echo editing the registry as follows (and then reopen your CMD windows):
echo.
echo Location: HKEY_CURRENT_USER\Software\Microsoft\Command Processor
echo Item: DelayedExpansion
echo Type: dword
echo Value: 1
echo.
echo ================================================================================
echo.
:TheEnd
Thank you James L and User.
James:
Post 1: I though about asking some one to do it for me but then I would never learn anything from it. ignoring your telling me to the the towel in i got a working program.
Post 2: Very very useful post. Not only did it have code (i got to work no problem) you gave a description of how you used it. the first code is going to take me a while to decode what is what and how you did it. The second code it VERY HELPFUL, its well documented and i understand more of whats going on it it.
User:
This ended up being what i used to get my program to work. I had to keep it simple :)
Thank you both for your help with this posted problem.
James: thank you very much for all the code and useful information that your second post was teeming with.
This is the final working code for copying pictures from an SD card to a specific user named folder sorted by year then month then project name. This is set for the SD Drive to be drive letter "F:" you can change it to what you need or delete "#SET cameradrive=F:" and remove the "REM" from the line above and it will prompt the user for the drive letter. It takes the user input and makes it all capitals to make a cleaner looking folder. One thing to note: this doesn't work if the folder name has a space in it. I have to figure out how to fix that (ill be posting a question on it here). It then opens the folder in explorer so you can verify that everything went OK. After you have checked then you can delete the files on the SD card by pressing "y" and hitting enter. If you don't want to delete them then press "n" and hit enter. This copies EVERY PICTURE on the SD card in the nested folder so if you have multiple photos you want to go different places this wont work for you. also if your pictures aren't jpg then just change the "SET type=" to what ever your file type is. I placed a program called "USB Ejector" into the root of the SD card so that when the batch file is completed it automatically safely removes the card from windows.
# echo on
# SET type=jpg
# SET userfolder=C:
#cd /dy:\landis\public\am_class
#REM SET /P cameradrive=Enter Camera Drive Letter (ie D:) and hit Enter:
#SET cameradrive=F:
set /p foldername=Type Folder name and hit Enter:
#REM This makes everything uppercase.
# SETLOCAL ENABLEDELAYEDEXPANSION
# SET _SAMPLE="%foldername%"
# CALL :UCase _SAMPLE _RESULTS
# ECHO.%_RESULTS%
# CALL :LCase _SAMPLE _RESULTS
# ECHO.%_RESULTS%
# ENDLOCAL
# GOTO:EOF
# :LCase
# :UCase
# :: Converts to upper/lower case variable contents
# :: Syntax: CALL :UCase _VAR1 _VAR2
# :: Syntax: CALL :LCase _VAR1 _VAR2
# :: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
# :: _VAR2 = NAME of variable to hold the converted value
# :: Note: Use variable NAMES in the CALL, not values (pass "by reference")
# SET _UCase=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
# SET _LCase=a b c d e f g h i j k l m n o p q r s t u v w x y z
# SET _Lib_UCase_Tmp=!%1!
# IF /I "%0"==":UCase" SET _Abet=%_UCase%
# IF /I "%0"==":LCase" SET _Abet=%_LCase%
# FOR %%Z IN (%_Abet%) DO SET _Lib_UCase_Tmp=!_Lib_UCase_Tmp:%%Z=%%Z!
# SET %2=%_Lib_UCase_Tmp%
#REM GOTO:EOF
#REM
# SET foldername=%_RESULTS%
#REM SETTING THE YEAR AND MONTH VARIABLES
# SET yyyy=%date:~10,4%
# SET mm=%date:~4,2%
#REM CREATING THE FOLDERS WITH THE NAMES AND NESTING THEM CORRECTLY
# mkdir %yyyy%
# cd %yyyy%
# mkdir "MSU Orders"
# cd "MSU Orders"
# mkdir %mm%
# cd %mm%
# mkdir "%foldername%"
# cd "%foldername%"
#REM COPY THE CONTENTS OF THE CAMREA PIC FOLDER TO THE NEW FOLDER
# xcopy /e /v %cameradrive%\DCIM\100NIKON "\\landis\public\am_class\%yyyy%\%mm%\%foldername%\"
# explorer.exe \\landis\public\am_class\%yyyy%\%mm%\%foldername%\
#REM Delete the originals prompt and then actions
# SET /P delete=Delete Original Photos from Camera (y/n)?
# IF /I %delete%==y GOTO :dely
# IF /I %delete%==n GOTO :deln
# GOTO :deln
# :dely
# cd /d%cameradrive%\DCIM\100NIKON
# del /q *.*
# GOTO :done
# :deln
# GOTO :done
# :done
# cd /dc:\
# F:\USB_Disk_Eject.exe /removethis
# pause

Add information to beginning of file using a BAT process, but keep file name convention

I am new to Stackoverflow, so I hope I am posting this in the correct area. I have been searching for an answer to my question for quite a while. I am attempting to add some information to the beginning of a file. The file that needs the information has a dynamic file name (Never the same, except for first 5 characters). You can see in my code the information I am needing in my file. The name of the file original file is LBL043629201313114512.DTA. The consist about the file name is "LB04xxxx. The XXXX is what I am searching for to make sure I grab the correct file.
I need the output to be the original file name (LBL......DTA) with the collected data at the beginning of the file. Any help would be great.
set /p STORE=Please enter store number:
set /p NAME=Please enter name:
set /p ADDRESS=Please enter address:
set /p CITY=Please enter address:
set /p STATE=Please enter State:
set /p ZIP=Please enter ZIP:
set /p SPECIAL=Add any Special Instructions:
(
echo %NAME%
echo %ADDRESS%
echo %CITY% %STATE% %ZIP%
echo %SPECIAL%
) > address.txt
copy address.txt+LBL04%STORE%*.DTA=test.txt
just append two lines at the end:
del /q LBL04%STORE%*.DTA
ren test.txt LBL04%STORE%*.DTA
Be sure, you don't need the original .DTA again (better, make a backup as long as you test your script
#ECHO OFF
SETLOCAL
FOR %%i IN (store name address
city state zip
special target) DO (SET %%i=)
set /p STORE=Please enter store number:
set /p NAME=Please enter name:
set /p ADDRESS=Please enter address:
set /p CITY=Please enter address:
set /p STATE=Please enter State:
set /p ZIP=Please enter ZIP:
set /p SPECIAL=Add any Special Instructions:
FOR %%i IN (store name address
city state zip
special) DO IF NOT DEFINED %%i (SET %%i= )
(
ECHO.%NAME%
ECHO.%ADDRESS%
ECHO.%CITY% %STATE% %ZIP%
ECHO.%SPECIAL%
) > address.txt
FOR /f %%i IN (
'dir /b /a-d /o-d lbl04%store%*.dta'
) DO IF NOT DEFINED target SET target=%%i
IF NOT DEFINED target ECHO LBL04%STORE%*.DTA NOT found&GOTO :EOF
copy address.txt+%target%=test.txt >nul
MOVE test.txt %target% >nul
type %target%
Obviously, you should try this against a copy of your real data first, not your live data.
The first FOR ensures that the variable names in the list are removed from the environment so that if they have an existing value then pressing enter at any of the prompts, that value would have been retained.
The second FOR loop ensures that each of the entered variables HAS a value. Note that target is NOT included in this group. There is a space between the = and the ).
With a simple SET instruction, SPACES are significant. The syntax (SET var=) or equivalently, SET "var=" ensures that the variable var is set to [nothing]. The problem with SET var= is that some editors leave terminal spaces on the line and under those circumstances, var will be set to those terminal spaces - and they're a little difficult to see. Also, SET var =... will set the variable "var" not the variable "var" - but that's a whole 'nother story.
Note that the ECHO statements now have a dot directly following the ECHO. The statement ECHO or ECHO will cause ECHO to report its state, and ECHO is off would appear in the output. Adding the "." gives ECHO something to chew on and it produces the line content beyond the .
The dir instruction in the next statement produces a directory list in /b basic form (filenames only) /a-d and no directory names /o-d in reverse-date order. The FOR /f is a mechanism for reading the output of the dir /b ... instruction, line-by-line. The contents of the next line of "input" read is applied to %%i each iteration. Therefore, the first filename matching LBL04%STORE%*.DTA encountered will be SET into target and since target is now set, any further lines will be ignored because of the if not defined gate.
If there were no matching files, target would not be defined (it was deleted in the very first for loop) so it's possible to produce an error message.
Otherwise, concatenate the files to test.txt and then the move statement actually replaces the file "%target% (which we know exists) with the concatenated version.
The >nul on each of these last two lines suppreses the message '1 file copied/moved`
Job done! New file TYPED as evidence

Resources