Windows Batch: What does the "~" do? [duplicate] - batch-file

This question already has answers here:
What does %~d0 mean in a Windows batch file?
(9 answers)
Closed 8 years ago.
I was just wondering what the "~" symbol does in a batch file, I know that it's associated with variables.
Can I have some examples of what it does?
Thanks.

It depends on the command on which ~ is used as dbenham and Magoo already wrote. In general it means: Get the value of a variable (loop or environment variable) or an argument string passed to the batch file with a modification.
A very simple example:
There is a batch file test.bat with content:
#echo Parameter 1 as specified: %1
#echo Parameter 1 (no quotes): %~1
which is started with
test.bat "C:\Program Files\Internet Explorer\iexplore.exe"
The double quotes are necessary because of the spaces in path.
The batch file outputs:
Parameter 1 as specified: "C:\Program Files\Internet Explorer\iexplore.exe"
Parameter 1 (no quotes): C:\Program Files\Internet Explorer\iexplore.exe
So in this example ~ results in getting value of first parameter without double quotes.
As dbenham already wrote, enter in a command prompt window following commands and read the help output in the window.
help call or call /?
help for or for /?
help set or set /?
On many commands strings with spaces or other special characters – see last help page output after entering cmd /? – must be enclosed in double quotes. But others require that the double quotes are removed like on a comparison of two double quoted strings with command if or the double quotes are not wanted like on using echo.
One more example:
#echo off
if /I "%~n1" == "iexplore" echo Browser is Internet Explorer.
if /I "%~n1" == "opera" echo Browser is Opera.
if /I "%~n1" == "firefox" echo Browser is Firefox.
On this example ~n results in just getting the file name without double quotes, path and file extension from string passed as first parameter to the batch file.
Argument 0 is the currently executed batch file as it can be demonstrated with:
#echo off
echo Batch file was called with: %0
echo Batch file is stored on drive: %~d0
echo Batch file is stored in folder: %~dp0
echo Batch file name with extension: %~nx0

Depends on context which you've not provided.
For instance, if there is a filename in %%a, then %%~za will return the filesize, %%~ta the file date/time. Other times it may be a substring operator, such as %fred:~1,6% (the substring of fred, skipping the first 1 and selecting the next 6 maximum.

Related

how to make batch file handle spaces in file names

I have the following batch file to make git diff invoke spreadsheet compare UI in windows. So I'm trying to pass the git diff's 2nd (old file) and 5th (new file) arguments to spreadsheet compare in order to make it compare the file using git diff.
So now, this batch file only successfully handles files with NO spaces in the file names, it CANNOT handle files with spaces in the file names.
What code should I add to this script to make this batch code handles file with spaces:
#ECHO OFF
set path2=%5
set path2=%path2:/=\%
ECHO %2 > tmp.txt
dir %path2% /B /S >> tmp.txt
C:/"Program Files"/"Microsoft Office"/root/vfs/ProgramFilesX86/"Microsoft Office"/Office16/DCF/SPREADSHEETCOMPARE.EXE tmp.txt
It currently throw errors like this:
Unhandled Exception: System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.IO.Path.GetFileName(String path)
at ProdianceExcelCompare.Form1.StatusReady()
at ProdianceExcelCompare.Form1.Init()
at ProdianceExcelCompare.Form1..ctor(String instructionFile)
at ProdianceExcelCompare.Program.Main(String[] args)
fatal: external diff died, stopping at London comparison.xlsx
See the following answers on Stack Overflow:
How to set environment variables with spaces?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
They explain the recommended syntax set "VariableName=variable value" to define an environment variable and the reasons recommending this syntax.
Why does ECHO command print some extra trailing space into the file?
It explains why the space character left to redirection operator > on an ECHO command line is also written into the file as trailing space and how to avoid this safely on variable text written into the file.
See also Microsoft documentation about Using command redirection operators.
On other command lines than ECHO a space left to > is usually no problem.
It is in general wrong to use multiple times " within an argument string like a file or folder path. There should be just one " at beginning and one " at end. This is explained by help of Windows command processor output on last help page on running in a command prompt window cmd /?.
The Microsoft documentation about Naming Files, Paths, and Namespaces explains that the directory separator on Windows is \ and not / and therefore / should not be used in batch files on Windows in file/folder paths.
The help output on running in a command prompt window call /? explains how the arguments of a batch file can be referenced with which modifiers.
The code rewritten according to information posted above and on the referenced pages:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
>"tmp.txt" echo %2
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
The first line in tmp.txt contains the second argument as passed to the batch file, i.e. without or with surrounding double quotes.
The following code is necessary to write the second argument safely always without " into file tmp.txt even on second argument passed to the batch file is "Hello & welcome!":
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
set "Argument2=%~2"
setlocal EnableDelayedExpansion
echo !Argument2!>"tmp.txt"
endlocal
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
>tmp.txt echo %~2 cannot be used as not working for something like "Hello & welcome!". Windows command processor would interpret the first string separated by normal space, horizontal tab, comma, equal sign, or no-break space (in OEM code pages) delimited string after & as command or application to execute as described by single line with multiple commands using Windows batch file.
"tmp.txt" could be written everywhere in both batch files also with just tmp.txt. But it is never wrong to enclose the complete file/folder argument string in double quotes even on not being really necessary because of the string does not contain a space or one of these characters &()[]{}^=;!'+,`~. So it is good practice to always enclose a complete file/folder argument string in double quotes. For example running a replace on both batch files searching for tmp.txt and using as replace string %TEMP%\%~n0.tmp would result in using instead of tmp.txt in current directory a temporary file with name of batch file as file name and file extension .tmp in directory for temporary files independent on what is the name of the batch file and what is the path of the directory for temporary files.
The last suggestion is reading this answer for details about the commands SETLOCAL and ENDLOCAL.
The temporary file should be also deleted finally before reaching an exit point for batch file execution.
You can use quotes as below:
It treats the string in quotes as a title of the new command window. So, you may do the following:
start "" "yourpath"
Found it in the below link :
https://ccm.net/forum/affich-16973-open-a-file-with-spaces-from-batch-file

Batch script calling its own name instead of files of a certain type?

cd %cd%
ffmpeg -i %cd%/%04d.png out.mp4
A script with just this in it works completely fine and outputs exactly what I need it to, but:
:: A simple script to convert a png or jpg image sequence to an
mp4 file with ffmpeg
cls
#echo off
title PNG2MP4
color C
echo Ensure you have ffmpeg installed and setup in your environment variables or this script won't work.
:QUERY
echo This will convert all image files in the following directory to a single mp4,
echo %cd%
echo are the files PNGs or JPEGs(PNG/P/JPG/J/CANCEL)?
set/p "ch=>"
if /I %ch%==PNG goto CONVERTPNG
if /I %ch%==P goto CONVERTPNG
if /I %ch%==JPG goto CONVERTJPG
if /I %ch%==J goto CONVERTJPG
if /I %ch%==CANCEL goto :eof
echo Invalid choice & goto QUERY
:CONVERTPNG
cd %cd%
ffmpeg -i %cd%/%04d.png out.mp4
:CONVERTJPG
cd %cd%
ffmpeg -i %cd%/%04d.jpg out.mp4
This more complex version of the script fails, outputting:
C:\tmp/img2mp4.bat4d.jpg: No such file or directory
Why is it no longer calling the files that it did before and is there an easy fix for this?
Here is my suggestion for the batch file:
#echo off
rem A simple script to convert a png or jpg image sequence to an mp4 file with ffmpeg
cls
title PNG2MP4
color C
echo Ensure you have ffmpeg installed and setup in your environment variables
echo or this script won't work.
echo/
echo This will convert all image files in the following directory to a single mp4:
echo/
echo %cd%
echo/
%SystemRoot%\System32\choice.exe /C PJC /N /M "Are the files PNGs or JPEGs or Cancel (P/J/C)? "
if errorlevel 3 color & goto :EOF
echo/
if errorlevel 2 (
ffmpeg.exe -i %%04d.jpg out.mp4
) else (
ffmpeg.exe -i %%04d.png out.mp4
)
color
The character % must be escaped in a batch file with one more % to be interpreted as literal character which was the main problem causing the batch file not working as expected. %0 references the string used to start the batch file which was img2mp4.bat. So %04d.jpg concatenated img2mp4.bat with 4d.jpg and the result was running ffmpeg.exe with img2mp4.bat4d.jpg as file name instead of the argument string %04d.jpg.
To reference one or more files/folders in current directory the file/folders can be simply specified in arguments list of a script or application with no path. This is explained in Microsoft documentation about Naming Files, Paths, and Namespaces. This page describes further that on Windows the directory separator is the backslash character \ and not the forward slash / as on Linux and Mac. / is used on Windows mainly for options as it can be seen on line with command CHOICE because of this character is not possible in file/folder names. - is used on Linux/Mac for options which is possible also in file/folder names even as first character of a file/folder name. So on Windows \ should be always used as directory separator although the Windows kernel functions for file system accesses automatically correct / in file/folder names to \.
CHOICE is much better for prompting a user to take a choice from several offered options than the command SET with option /P. set/p is syntactically not correct at all because of command set should be separated with a space from option /P which should be separated with a space from next argument variable=prompt text. set/p forces cmd.exe to automatically correct the command line to set /p. Batch files should be syntactically correct coded and not depend on automatic error corrections of Windows command processor.
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.
call /? ... explains how to reference batch file arguments.
echo /?
rem /?
cls /?
title /?
color /?
set /?
choice /?
if /?
goto /?
Further I suggest to read:
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
Single line with multiple commands using Windows batch file
ECHO. FAILS to give text or blank line - Instead use ECHO/
Where does GOTO :EOF return to?

Why is a subfolder with space recognized as file on execution of my batch script?

In my code I'm searching for only files in folder and all subfolders. When the name of subfolder has one blank (space) between the words this subfolder is recognized as a file, too. This is not correct behavior. The parameter /a-d doesn't help here.
#echo on
Setlocal EnableDelayedExpansion
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
set string1=Well-Formed and valid
set string2=Well-Formed, but not valid
set string3=Not well-formed
set /a loop=0
set /a loop1=0
set /a loop2=0
set /a loop3=0
for /f %%a in ('dir /b /a-d /s %input%') do (
CALL jhove -m PDF-hul -h xml -o %output%\%%~na.xml %%a
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
The output of the script on running in directory C:\Users\NekhayenkoO\jhove-beta:
Setlocal EnableDelayedExpansion
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
set string1=Well-Formed and valid
set string2=Well-Formed, but not valid
set string3=Not well-formed
set /a loop=0
set /a loop1=0
set /a loop2=0
set /a loop3=0
for /F %a in ('dir /b /a-d /s "C:\Users\NekhayenkoO\test\"') do (
echo Verarbeite %~na
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\%~na.xml" "%a"
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
(
echo Verarbeite 757419577
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\757419577.xml" "C:\Users\NekhayenkoO\test\757419577.pdf"
if !ERRORLEVEL! EQU 0 (echo Errorlevel equals !errorlevel! )
if !ERRORLEVEL! GEQ 1 (Errorlevel equals !errorlevel! )
set /a loop3+=1
)
Verarbeite 757419577
Errorlevel equals 0
Verarbeite GBV58575165X
Errorlevel equals 0
Verarbeite GBV85882115X
java.lang.ClassCastException: edu.harvard.hul.ois.jhove.module.pdf.PdfSimpleObject cannot be cast to edu.harvard.hul.ois.jhove.module.pdf.PdfDictiona
at edu.harvard.hul.ois.jhove.module.PdfModule.readDocCatalogDict(PdfModule.java:1344)
at edu.harvard.hul.ois.jhove.module.PdfModule.parse(PdfModule.java:521)
at edu.harvard.hul.ois.jhove.JhoveBase.processFile(JhoveBase.java:803)
at edu.harvard.hul.ois.jhove.JhoveBase.process(JhoveBase.java:588)
at edu.harvard.hul.ois.jhove.JhoveBase.dispatch(JhoveBase.java:455)
at Jhove.main(Jhove.java:292)
Errorlevel equals 0
Verarbeite GBV858852357
Errorlevel equals 0
Verarbeite nicht_valide_PDF
Errorlevel equals 0
Verarbeite not_Wellformed_intern
Errorlevel equals 0
Verarbeite pp1788_text
Errorlevel equals 0
Verarbeite Rosetta_Testdatei
Errorlevel equals 0
Verarbeite script
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite java
Errorlevel equals 0
Verarbeite GBV58525785X
Errorlevel equals 0
Verarbeite GBV58574517X
Errorlevel equals 0
Drücken Sie eine beliebige Taste . . .
What is jhove?
Oleg Nekhayenko, you have asked several jhove related questions in the last days, but you have always forgotten to explain what jhove is which is important to know for all of your questions.
Therefore I searched in world wide web for jhove, found very quickly the homepage
JHOVE | JSTOR/Harvard Object Validation Environment, read quickly its documentation and command-line interface description and finally downloaded also jhove-1_11.zip from SourceForge project page of JHOVE.
All this was done by me to find out that jhove is a Java application which is executed on Linux and perhaps also on Mac using the shell script jhove and on Windows the batch file jhove.bat for making it easier to use by users.
You could have saved yourself and all readers of your questions a lot of time if you would have written jhove.bat instead of just jhove in your code snippets or at least mentioned anywhere that jhove is a batch file.
Assigning a value/string to an environment variable
I suggest to read first the answer on
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
and next look on these two lines:
set "input=C:\Users\NekhayenkoO\test\"**
set "output=C:\Users\NekhayenkoO\outputxml\"**
I don't know why two asterisks are at end of those 2 command lines. But that does not really matter as both asterisk are ignored on assigning the two paths to the two environment variables.
This can be seen on posted output of the batch file as there is no asterisk output on the lines:
for /F %a in ('dir /b /a-d /s "C:\Users\NekhayenkoO\test\"') do (
CALL jhove -m PDF-hul -h xml -o "C:\Users\NekhayenkoO\outputxml\\757419577.xml" "C:\Users\NekhayenkoO\test\757419577.pdf"
There is no asterisk anywhere. So the environment variables input and output are obviously defined without the asterisks at end which is even good here.
Enclosing directory and file names in double quotes
The help output on running cmd /? in a command prompt window explains in last paragraph on last help page on which characters in a directory or file name double quotes must be used around complete directory/file name.
The space character is the string delimiting character on command line and therefore a directory or file name with a space must be always enclosed in double quotes.
Predefined environment variables on Windows
Opening a command prompt window and running set results in output of all environment variables defined for the the current user account including PATH and PATHEXT as also USERNAME and USERPROFILE.
The Wikipedia article about Windows Environment Variables explains the environment variables predefined by Windows. It is advisable to make use of them in batch files.
Execution of applications and scripts on Windows
If in a command prompt window or in a batch file just the file name of an application or script without file extension and without path is specified, the Windows command interpreter is searching first in current directory and next in all directories of environment variable PATH for a file with specified name having a file extension listed in environment variable PATHEXT. In this case Windows command interpreter is searching for jhove.*.
The values of the environment variables PATH and PATHEXT can be seen on opening a command prompt window and running in this window set path which results in output of all environment variables starting with the case-insensitive interpreted string PATH with their current values.
Next to know is that when Windows command interpreter searches for jhove.*, the NTFS file system returns the file names matching this search pattern sorted alphabetically. So if current directory or any of the directories listed in PATH have for example jhove.bat and jhove.exe, the NTFS file system returns first jhove.bat. This batch file is used by Windows command interpreter as file extension BAT is listed by default in PATHEXT.
But if the file system of the drive with jhove.* files is FAT, FAT32 or ExFat, the file system returns the file names matching the search pattern in order as stored in the file allocation table and therefore unsorted. So in case of a directory contains jhove.bat and jhove.exe on a drive with any FAT file system, it is unpredictable which file is executed by Windows command interpreter on specifying just jhove in a batch file.
For that reason it is always advisable to specify the application or script with file name and at least also with the file extension. And if possible the entire path to the application to run or the script to call should be also specified.
The Windows command interpreter does not need to search around by specifying the name of an application or script file with file extension and with complete path.
See also answer on Where is "START" searching for executables?
Calling a batch file versus running an application
A batch file is a script (text file) interpreted by Windows command interpreter line by line whereby a command block starting with ( and ending with matching ) is interpreted like a subroutine defined on one line.
An application is an executable (binary file) compiled with a compiler for a specific processor or processor family and therefore does not need to be interpreted anymore on execution. It contains already processor instructions (machine code).
Why the command call must be used to run another batch file from within a batch file is explained in detail by the answers on
How to call a batch file that is one level up from the current directory?
In a Windows batch file, can you chain-execute something that is not another batch file?
For that reason it is very important to know what jhove is. It is a batch file and must be therefore called with command call which answers the question How to process 2 for loops after each other in batch?
For help on command call open a command prompt window and run call /?. The output help explains also which placeholders exist to reference arguments of the batch file whereby argument 0 is the name of the batch file.
Which command lines contains jhove.bat?
On unexpected behavior on calling a batch file from another batch file it is important to know the code of the called batch file as well because the error could be in code of called batch file.
Code of jhove.bat as stored in jhove-1_11.zip without instruction comments:
#ECHO OFF
SET JHOVE_HOME=%~dp0
SET EXTRA_JARS=
REM NOTE: Nothing below this line should be edited
REM #########################################################################
SET CP=%JHOVE_HOME%\bin\JhoveApp.jar
IF "%EXTRA_JARS%"=="" GOTO FI
SET CP=%CP%:%EXTRA_JARS
:FI
REM Retrieve a copy of all command line arguments to pass to the application
SET ARGS=
:WHILE
IF %1x==x GOTO LOOP
SET ARGS=%ARGS% %1
SHIFT
GOTO WHILE
:LOOP
REM Set the CLASSPATH and invoke the Java loader
java -classpath %CP% Jhove %ARGS%
Well, this is a not good written batch code for following reasons:
The commands setlocal and endlocal are not used in batch file to control the life time of variables used by this batch file. See answer on change directory command cd ..not working in batch file after npm install for more details. npm.bat is also a not good coded batch file like jhove.bat as it turned out.
The command line SET JHOVE_HOME=%~dp0 defines the environment variable JHOVE_HOME with drive and path of storage location of jhove.bat. The path returned by %~dp0 ends always with a backslash. If jhove*.zip was extracted into a directory with 1 or more space in complete path, care must be taken wherever JHOVE_HOME is finally used to enclose the final string in double quotes.
The command line SET CP=%JHOVE_HOME%\bin\JhoveApp.jar defines the environment variable CP by concatenating path to batch file jhove.bat with a fixed path and name of the Java package. Here is already a small mistake as %~dp0 is a path always ending with a backlash concatenated with a string starting with a backslash. So there are two backslashes finally in path to the Java package file. But Windows kernel handles this error in path and therefore it does not really matter.
The environment variable CP is referenced unmodified with no EXTRA_JARS defined by the user finally on command line java -classpath %CP% Jhove %ARGS%. The error here is %CP% is specified without being enclosed in double quotes which results in unexpected behavior if jhove*.zip was extracted indeed by the user into a directory with 1 or more spaces in complete path.
A percent sign is missing at end of command line SET CP=%CP%:%EXTRA_JARS.
The writer of jhove.bat did not know obviously anything about %* which on usage of last command line instead of %ARGS% makes the WHILE loop above completely useless.
Much better for jhove.bat would be:
#echo off
setlocal EnableExtensions
set "JHOVE_HOME=%~dp0"
set "EXTRA_JARS="
REM NOTE: Nothing below this line should be edited
REM #########################################################################
set "CP=%JHOVE_HOME%bin\JhoveApp.jar"
if not "%EXTRA_JARS%"=="" set "CP=%CP%:%EXTRA_JARS%"
rem Set the CLASSPATH and invoke the Java loader
java.exe -classpath "%CP%" Jhove %*
endlocal
The executable java.exe must be found via environment variable PATH by Windows command interpreter.
Final batch code for usage
I suggest to use the following code for this task in case of jhove.bat should not be modified to above working code:
#echo off
setlocal EnableExtensions
set "InputFolder=%USERPROFILE%\test"
set "OutputFolder=%USERPROFILE%\outputxml"
echo Searching for bin\JhoveApp.jar in:
echo.
set "SearchPath=%CD%;%PATH%"
set "SearchPath=%SearchPath:)=^)%"
for /F "delims=" %%I in ('echo %SearchPath:;=^&ECHO %') do (
echo %%I
if exist "%%~I\bin\JhoveApp.jar" (
set "JHOVE_HOME=%%~I"
goto RunJHOVE
)
)
echo.
echo Error reported by %~f0:
echo.
echo Could not find bin\JhoveApp.jar in current directory and folders of PATH.
echo.
endlocal
pause
goto :EOF
:RunJHOVE
if "%JHOVE_HOME:~-1%" == "\" (
set "CP=%JHOVE_HOME%bin\JhoveApp.jar"
) else (
set "CP=%JHOVE_HOME%\bin\JhoveApp.jar"
)
echo.
echo Using %CP%
md "%OutputFolder%" 2>nul
rem for /F %%I in ('dir /A-D /B /S "%InputFolder%\*" 2^>nul') do (
rem java.exe -classpath "%CP%" Jhove -m PDF-hul -h xml -o "%OutputFolder%\%%~nI.xml" "%%I"
rem )
for /R "%InputFolder%" %%I in (*) do (
java.exe -classpath "%CP%" Jhove -m PDF-hul -h xml -o "%OutputFolder%\%%~nI.xml" "%%I"
)
endlocal
The input and output folder paths are defined without backslash at end and without asterisk using predefined environment variable USERPROFILE.
A slightly modified code written by Magoo in his answer on Find the path used by the command line when calling an executable is used to find Java package of JHOVE. The batch file prints the folders it is searching for in case of the file could not be found which results in an error message and halting batch execution until the user presses any key.
The class path variable CP is created with taking into account if folder path ends with a backslash or not. Folder paths in PATH should be defined without backslash at end, but there are always installers which add folder paths not 100% correct to PATH. However, it does not really matter if the result would be \\ anywhere within a path as Windows kernel handles this. That's the reason why if exist "%%~I\bin\JhoveApp.jar" also always works although this file existence test could be also done with two backslashes in path depending on folder path in PATH.
Next the output folder is created without checking first if the folder is already existing and without checking if folder creation was successful at all.
The batch code contains two solutions for running jhove on each file found recursively in input folder path. The first one is commented out. It would have the advantage to work also for hidden and system files. The second solution does not work for hidden and system files, but this is most likely not necessary here. The second solution is therefore the preferred one.
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.
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
pause /?
set /?
setlocal /?
And read also the Microsoft articles:
Microsoft's command-line reference
Using command redirection operators
Testing for a Specific Error Level in Batch Files

About Copying Files

I want to copy some files to same destination.
Files which will be copied are listed in a text file.
So, how to read file list from text file and copy via using cmd
command?
I tried this command:
for /f "delims=" %%L in (foo.txt) do copy "%%L" new_folder
Similar question was asked in this website, I know that. When I use this command, files will be copied; but folders which include these files won't be copied.
I want to copy files with their directories.
What should I do? (Sorry for my awful English.)
You use %%L in a batchfile and %L when typing interactivly.
Your command, depending on other factors, should have a path specified for new_folder.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. Single % sign at command prompt and double % sign in a batch file.
.
--
Ok ,I have solved my problem via searching another cmd command:
for /f "delims=" %%i in (filelist.txt) do echo F|xcopy "-Source root folder-\%%i" "-Destination folder-\%%i" /i /z /y
In spite of the fact that I have solved my problem myself, thanks guys for your helps.
I appreciate it too much!

how to add switches to commands in cmd

hey guys very simple question, I need to know how to add an extension/switch into a command in cmd.
Also how would I do this to a command that I made? (batch file that is called when typed the name of)
Ex.
Traditional
ipconfig /all
Modifed
ipconfig -a
or
ipconfig /a
This is a simple example to go with the answer above.
#echo off
if /i "%~1"=="-a" ipconfig /all
if /i "%~1"=="/a" ipconfig /all
(don't call your batch file ipconfig.bat - never use system command names for a batch file):
Cmd.exe provides the batch parameter expansion variables %0 through
%9. When you use batch parameters in a batch file, %0 is replaced by
the batch file name, and %1 through %9 are replaced by the
corresponding arguments that you type at the command line. To access
arguments beyond %9, you need to use the shift command. For more
information about the shift command, see Shift The %* batch parameter
is a wildcard reference to all the arguments, not including %0, that
are passed to the batch file.
For example, to copy the contents from Folder1 to Folder2, where %1 is
replaced by the value Folder1 and %2 is replaced by the value Folder2,
type the following in a batch file called Mybatch.bat:
xcopy %1\*.* %2
To run the file, type:
mybatch.bat C:\folder1 D:\folder2
Copied from MSDN
create a batch file mytest.cmd with notepad and add the following
rem start parsing out first parameter indicated with %1
set parm1=%1
set arg1=%parm1:~2%
if "%arg1%"=="a" echo A was the parameter
now arg1 will hold a from your example without the - or /
if you run mytest -a you'll see A was the parameter
if you run mytest -b you won't see a thing...
(as a matter of fact you see every single comand that is in the cmd file which is handy for debugging, try adding #echo off at the first line of mytest.cmd to get rid of the noise)
try at the cmd prompt set /?, if /?, for /? or call /? to learn more about the commands available.

Resources