What I know about batch files25
September 24, 2014 by Kenneth Fisher
For a SQL Server guy it sometimes amazes me how often I’m in and out of batch files and how truly useful they can be. To that end here is all that I can remember about batch files (basically a text file that ends with .bat). Everyone seemed to like 15 years of experience with identity columns so I’m doing this in that same format. Also in the same way please feel free to comment with what you can remember and corrections for any mistakes you find.
- To create a batch file type batch commands into a text file and name it with a .bat extension.
- To run a batch file either double click on it in windows explorer, right click and hit Open, or type the name in a command shell (in the correct directory) and hit enter.
- ECHO ON to print the commands to the output.
- ECHO OFF to stop printing commands to the output.
- ECHO will write to the output.
- REM comments out a line. This line will be printed if ECHO is turned on.
- :: Also comments out the line but will not be printed if ECHO is turned on.
- You can pass in parameters by putting %1, %2, %3 etc in your bat file. These will corrispond to the 1st, 2nd, and 3rd parameters passed in to a limit of %9.
- %* is all parameters.
- SHIFT moves the parameters down one. So the second parameter is now %1, third parameter is %2 etc. This let’s you handle more than 9 parameters.
- If you call the parameters like this %~1, %~2, %~3 then the quotes(“”) surrounding the parameter will be stripped off.
- SET var=xxx xxx Declares the variable var and stores “xxx xxx” into it.
- ECHO %var% to print the contents of the variable var.
- Put : at the beginning of a line to create a label.
- Use GOTO : to jump to that label.
- IF condition (command) Run command if condition is true.
- IF EXIST command Run command if exists.
- NOT Checks if the condition is not true.
- Use == For equal to.
- Use or != for not equal to.
- CD change location to .
- : Change location to current directory of .
- . is the current directory.
- .. is the directory one above the current directory.
- COPY Copies the file to .
- COPY + Copies the contents of into .
- MOVE Moves the file to .
- DEL Deletes if it exists.
- TYPE prints the contents of to the output.
- CALL Executes .
- START Starts a command or program.
- | passes the output of to .
- ECHO |TIME or ECHO |DATE prints the time or date to the output.
- FIND “” outputs only the lines with in them from whatever input is passed.
- DIR |FIND “mystring” outputs only the rows with mystring from the DIR command.
- DIR > test.txt Copies the output of the DIR command to the file test.txt overwriting the file if it already exists.
- EXIT to leave the bat file and return to the calling code. is optional.
- Code to conditionally rename a file with the date
if exist "\\MyPath\ken_test.txt" ( rename \\MyPath\ken_test.txt ken_test_%date:~-4,4%%date:~-10,2%%date:~-7,2%.txt )
@ sets ECHO OFF for the current line.
@ECHO OFF is usually the first line of my batch files.
Very awesome. I’ll remember that one.
Thank you for sharing. You’ve got some good stuff here that will likely add to anyone’s bag of batch file tricks. I hadn’t seen some of these before. It’s good to have a crib-sheet like this for reference.
I’ll contribute one I didn’t see (the for statement):
dir \\BuildServer\BuildArea\2.0.*.0 /A:D /B /O:-N >dir.txt
for /F %%i in (dir.txt) do set Version=%%i
The above saves a sorted directory of folders to a file, and sets a variable with the last value.
You should take a look at PowerShell. It will blow your mind!
Thanks! I intend to learn PowerShell. It’s on my list. It’s just a REALLY long list.
Thank you for a great reference.
Here’s another little goodie:
Dir >> test.txt appends the output of the Dir command to the file, rather than overwriting it. This also works for Type, and any other command that can be redirected.
Awesome. That’s a helpful one.
TYPE | more
prints the contents of to the output but 1 page a time. The first line is more typework but safer because if you type MORE > you overwrite your file.
XCOPY /R : copy entire subdirectories and its subdirectories. But it is deprecated. On newer systems better use ROBOCOPY.
SET DIRCMD= : if you always use certain parameters for your dir, you can put them in the SET DIRCMD so they become the default.
PROMPT: change the dos-prompt.
DISKCOPY : copy a floppy disk (does anyone still use those????? 🙂 )
SHUTDOWN : shuts down the computer (without parameters, it just shows the parameters!)
TASKKILL : kill a process. You can use the processid or the name of the process.
HELP: shows the doscommands that exist.
xxxxx /? : to get help on the parameters of any command
CLS : clear the screen to clean up the mess. Works also in Powershell.
RUNAS : to run something using other credentials then the current ones
echo xxx > : write the output to file OVERWRITING the file
echo xxx >> : write the output to file ADDING it to the file if it exists.
somecommand > %1> : writes the output of the command in file1 and writes the errors in file 2.
echo|date > c:\z\x.txt %1> c:\z\xx.txt
The echo|date gives an error and it will be written file xx.txt
I really like the ECHO |TIME o DATE trick. After +- 25 years of DOS, I didn’t know that trick. I used this
date < with in only a CR/LF.
How to create a file with CR/LF in it?
COPY CON c:\x\crlf.txt
Then hit the return-key (don’t mind the message if the file already exists and answer Yes) and then hit F6 and enter. (you copy from the console to a file, so everything you type will be copied into the file. F6+enter will close the file)
In some situations it’s easier to get permission to run a batch file than a PS script.
Here’s a good routine I found elsewhere on the internet for renaming files with a date stamp.
ren Daily_File.zip Daily_File_%date:~-4,4%%date:~-10,2%%date:~-7,2%.zip
Very nice. I’ll have to remember that one.
I have done a lot of automation with batch files. Here are some things that I have found very useful.
Call : parm1 parm2 – This effectively calls as a subroutine.
Goto :EOF – This is a return from a Call.
In use, the pattern looks like this:
Call : Param1 Param2 …
:: Parameters passed to the subroutine look like command line parameters.
Echo %1 – Param1
Echo %2 – Param2
Here are a few other useful techniques:
Echo. – This echos a blank line.
Set EnvVar=%EnvVar:ExistingWord=NewWord – This replaces a given substring in the environment variable
If /I “%EnvVar%”==”%EnvVar:ExistingWord=%” … – This checks if a substring is in the environment variable.
%EnvVar:~1,5% – This extracts a substring from the environment variable.
%~f1 expands %1 to a fully qualified path name
%~d1 expands %1 to a drive letter
%~p1 expands %1 to a path
%~n1 expands %1 to a file name
%~x1 expands %1 to a file extension
%~s1 expanded path containing 8.1 short names only
%~a1 expands %1 to file attributes
%~t1 expands %1 to date/time of file
%~z1 expands %1 to size of file
Here is another pattern that I use a lot for automation:
Set CmdLine=type “path\Input File.txt”
For /f “tokens=1,2,3* delims=,” %%a In (‘%CmdLine%’) Do Call :ProcessLines “%%a” “%%b” “%%c”
This is a very powerful pattern. It executes the command in the CmdLine variable. It then spins through each line of output parsing it according to the delims list. It then breaks each line into however many chunks are specified by the tokens list putting the results in consecutive variables starting with the specified letter. It then executes whatever follows the “Do” keyword once for each line of output being parsed.
CmdLine can be any command line that can be executed at a command prompt includes console applications. If delims are left out, the default delimiter is space. Star in the tokens list means to include the rest of the line.
Don’t forget the humble Pause statement.
Sometimes it’s nice to give your user (or you) the option to bail out of the batch file.
Good point. Although almost all of the batch files I deal with at this point are unattended, meant for batch processing.
Another one :
TIMEOUT [/T] timeout [/NOBREAK] : wait for “timeout” seconds.
Do you have any idea how much time I spent looking for that flipping command! 🙂
All I could find is that there was no way to do it. I ended up doing a ping that I knew was going to fail occasionally and just ignoring the error.
If you want to use the ping, you can use this one:
ping -n 127.0.0.1 : this ping goes about 1 per second. 🙂
or in case you don’t want the output
ping -n 5 127.0.0.1 > nul:
Excellent ideas. Wish I had thought of them at the time. The TIMEOUT command looks like it’s going to do what I need though.
If you need the path of the currently executing batch file:
Found at: lifehacker.com/5310255/use-relative-paths-in-your-batch-files
Very nice. Thanks!
In more recent versions of Windows I’ve started using TIME /T and DATE /T for time and date strings.
Thanks! These things change every now and again and it can be hard to keep up.
[…] means I pipe (|) information from one command to another. Something which is very natural to anyone used to DOS & bat files. In this particular case I’ve piped the output of Get-ChildItem to Where-Object in order to […]
[…] easily be used to run a script or stored procedure on a remote SQL Server. Combining this with a bat file (yes, again older technology) and an Enterprise scheduler (because not all of us use SQL Server […]
[…] is a list of common DOS/CMD commands. I’ve also got a post here where I go over a bunch of things useful in batch files, some of which you might find useful here […]
[…] to start, in batch, cmdshell, or DOS (whatever you want to call it) you can use certain environment variables in your code. For example %programfiles(x86)% that Kendra […]