DOS Batch - File Examples

A collection of batch files.



TOP
2008-01-01

Classic FTP - Executing a FTP script

Description:

The FTP command support the "-s:ftpscript.txt" option. The FTP commands listed in ftpscript.txt will automatically run after FTP starts. The FTP command can be started from a batch file.

Example:
  • FTP -v -i -s:ftpscript.txt
See also command line help: "C:>ftp -?"
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
open example.com
username
password
!:--- FTP commands below here ---
lcd c:\MyLocalDirectory
cd  public_html/MyRemoteDirectory
binary
mput "*.*"
disconnect
bye
Script Output:
 DOS Script Output
ftp> open example.com
User (Username:(none)):

ftp> !:--- FTP commands below here ---
ftp> lcd c:\MyLocalDirectory
Local directory now c:\MyLocalDirectory.
ftp> cd  public_html/MyRemoteDirectory
ftp> binary
ftp> !: mput "*.*"
ftp> disconnect
ftp> bye

TOP
2008-01-01

DOS Batch - Advanced Menu - Toggle menu options, persist settings for the next run

Description: Example - Installation Framework.

This example shows how to enhance a program with persistent settings that can be changed using a menu.

I.e.:

  • Choose 1 to change the 'Install version' from 'Client' to 'Server'.
  • Choose 1 again to change the 'Install version' back to 'Client'.
  • Choose 2 to change the 'Size of installation' from Full to 'Regular'.
  • Choose 2 again to change the 'Size of installation' to 'Mini'.
  • Choose 2 again to change the 'Size of installation' back to 'Full'.
  • Choose I to begin the installation. Note: this example is just a simulation and will not install anything on your PC.

Features:
  • simple and well structured
  • settings changeable at runtime
  • settings are persistent, the batch will remember all settings from the last run
  • progress indication during simulated file installation
Script: Download: BatchInstall.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
@ECHO OFF
REM.-- Prepare the Command Processor
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

REM.-- Version History --
REM         XX.XXX           YYYYMMDD Author Description
SET version=01.000-beta &rem 20051201 p.h.  initial version, providing the framework
REM !! For a new version entry, copy the last entry down and modify Date, Author and Description
SET version=%version: =%

REM.-- Set the window title
SET title=%~n0
TITLE %title%

REM.--initialize the variables
set FilePersist=%~dpn0+.cmd&     rem --define the filename where persistent variables get stored
set             SvrCli_choice=,Server,Client,
call:setPersist SvrCli=Server
set             bShowReadMe_choice=,Yes,No,
call:setPersist bShowReadMe=No
set             InstSize_choice=,Full,Regular,Mini,
call:setPersist InstSize=Full

rem.--read the persistent variables from the storage
call:restorePersistentVars "%FilePersist%"



:menuLOOP
echo.
echo.= Menu =================================================
echo.
for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo.  %%B  %%C
set choice=
echo.&set /p choice=Make a choice or hit ENTER to quit: ||(
    call:savePersistentVars "%FilePersist%"&   rem --save the persistent variables to the storage
    GOTO:EOF
)
echo.&call:menu_%choice%
GOTO:menuLOOP

::-----------------------------------------------------------
:: menu functions follow below here
::-----------------------------------------------------------

:menu_Options:

:menu_1   Install version              : '!SvrCli!' [!SvrCli_choice:~1,-1!]
call:getNextInList SvrCli "!SvrCli_choice!"
cls
GOTO:EOF

:menu_2   Size of installation         : '!InstSize!' [!InstSize_choice:~1,-1!]
call:getNextInList InstSize "!InstSize_choice!"
cls
GOTO:EOF

:menu_3   Show Readme.txt when finished: '!bShowReadMe!' [!bShowReadMe_choice:~1,-1!]
call:getNextInList bShowReadMe "!bShowReadMe_choice!"
cls
GOTO:EOF

:menu_
:menu_Execute:

:menu_I   Start Installation (simulation only)

set maxcnt=20
if /i "%InstSize:~0,1%"=="F" set maxcnt=11
if /i "%InstSize:~0,1%"=="R" set maxcnt=7
if /i "%InstSize:~0,1%"=="M" set maxcnt=3

echo.Simulating an installation for !maxcnt! files...
call:initProgress maxcnt
for /l %%C in (1,1,!maxcnt!) do (
    echo.Pretend to install !SvrCli! file %%C.
    call:sleep 1
    call:doProgress
)
call:sleep 1
TITLE %title%
if /i "%bShowReadMe:~0,1%"=="Y" notepad ReadMe.txt
GOTO:EOF

:menu_C   Clear Screen
cls
GOTO:EOF


::-----------------------------------------------------------
:: helper functions follow below here
::-----------------------------------------------------------


:setPersist -- to be called to initialize persistent variables
::          -- %*: set command arguments
set %*
GOTO:EOF


:getPersistentVars -- returns a comma separated list of persistent variables
::                 -- %~1: reference to return variable
SETLOCAL
set retlist=
set parse=findstr /i /c:"call:setPersist" "%~f0%"^|find /v "ButNotThisLine"
for /f "tokens=2 delims== " %%a in ('"%parse%"') do (set retlist=!retlist!%%a,)
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%retlist%
)
GOTO:EOF


:savePersistentVars -- Save values of persistent variables into a file
::                  -- %~1: file name
SETLOCAL
echo.>"%~1"
call :getPersistentVars persvars
for %%a in (%persvars%) do (echo.SET %%a=!%%a!>>"%~1")
GOTO:EOF


:restorePersistentVars -- Restore the values of the persistent variables
::                     -- %~1: batch file name to restore from
if exist "%FilePersist%" call "%FilePersist%"
GOTO:EOF


:getNextInList -- return next value in list
::             -- %~1 - in/out ref to current value, returns new value
::             -- %~2 - in     choice list, must start with delimiter which must not be '@'
SETLOCAL
set lst=%~2&             rem.-- get the choice list
if "%lst:~0,1%" NEQ "%lst:~-1%" echo.ERROR Choice list must start and end with the delimiter&GOTO:EOF
set dlm=%lst:~-1%&       rem.-- extract the delimiter used
set old=!%~1!&           rem.-- get the current value
set fst=&for /f "delims=%dlm%" %%a in ("%lst%") do set fst=%%a&rem.--get the first entry
                         rem.-- replace the current value with a @, append the first value
set lll=!lst:%dlm%%old%%dlm%=%dlm%@%dlm%!%fst%%dlm%
                         rem.-- get the string after the @
for /f "tokens=2 delims=@" %%a in ("%lll%") do set lll=%%a
                         rem.-- extract the next value
for /f "delims=%dlm%" %%a in ("%lll%") do set new=%%a
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" (SET %~1=%new%) ELSE (echo.%new%)
)
GOTO:EOF


:initProgress -- initialize an internal progress counter and display the progress in percent
::            -- %~1: in  - progress counter maximum, equal to 100 percent
::            -- %~2: in  - title string formatter, default is '[P] completed.'
set /a ProgressCnt=-1
set /a ProgressMax=%~1
set ProgressFormat=%~2
if "%ProgressFormat%"=="" set ProgressFormat=[PPPP]
set ProgressFormat=!ProgressFormat:[PPPP]=[P] completed.!
call :doProgress
GOTO:EOF


:doProgress -- display the next progress tick
set /a ProgressCnt+=1
SETLOCAL
set /a per=100*ProgressCnt/ProgressMax
set per=!per!%%
title %ProgressFormat:[P]=!per!%
GOTO:EOF




FOR /l %%a in (%~1,-1,1) do (ping -n 2 -w 1 127.0.0.1>NUL)
goto :eof
Script Output:
 DOS Script Output
= Menu =================================================

  Options:
  1  Install version              : 'Client' [Server,Client]
  2  Size of installation         : 'Full' [Full,Regular,Mini]
  3  Show Readme.txt when finished: 'No' [Yes,No]

  Execute:
  I  Start Installation (simulation only)
  C  Clear Screen

Make a choice or hit ENTER to quit:

TOP
2008-01-01

DOS Batch - Advanced Template - Template with version history, window title, delayed automatic exit

Description: This advanced batch template features:
  • Initialization of the command processor
  • Version History for manual script change tracking
  • Window title of choice
  • Delayed exit for unattended completion
Script: Download: BatchDelayOnExit.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
@ECHO OFF
REM.-- Prepare the Command Processor
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

REM.-- Version History --
REM         XX.XXX           YYYYMMDD Author Description
SET version=01.000-beta &rem 20051201 p.h.  initial version, providing the framework
REM !! For a new version entry, copy the last entry down and modify Date, Author and Description
SET version=%version: =%

REM.-- Set the window title
SET title=%~n0


REM.-- your code goes here
echo.Hello World


REM.-- End of application
FOR /l %%a in (5,-1,1) do (TITLE %title% -- closing in %%as&ping -n 2 -w 1 127.0.0.1>NUL)
TITLE Press any key to close the application&ECHO.&GOTO:EOF

TOP
2008-01-01

DOS Batch - File Search List - Quickly find a file on your hard drive

Description:

This batch creates a lookup list of all files on the C: drive.
When running the batch the first time type a hyphen in order to build the lookup list first.

Features:
  • The lookup list will be appended to the batch file itself.
  • Options: build/rebuild lookup list, or locate a file
  • Regular expressions are supported, see FINDSTR for details.
Script: Download: BatchListOfFiles.bat  
1.
2.
3.
4.
5.
6.
@REM....&SETLOCAL ENABLEEXTENSIONS&SETLOCAL DISABLEDELAYEDEXPANSION
@REM....&set /p s=FileSearch, type '-' to refresh lookup list: ||GOTO:EOF
@REM....&if .%s% NEQ .- echo.&findstr %s% "%~f0"&PAUSE&GOTO:EOF
@REM....&findstr /b /c:"@REM....&" "%~f0">"%~f0.txt"
@REM....&dir /s/b c:\ 1>>"%~f0.txt"&move /Y "%~f0.txt" "%~f0"
@REM....&GOTO:EOF
Script Output:
 DOS Script Output
FileSearch, type '-' to refresh lookup list: logoMed.gif

C:\Python22\tcl\tk8.3\images\logoMed.gif
Press any key to continue . . .

TOP
2009-12-22

DOS Batch - Find and Replace - Search a file and replace all occurrences of a string with another string

Description:

This batch allows string substitution in a text file. It parses each line of a text file for a particular string and replaces it with another string.
I.e. To replace all occurrences of "Yellow Submarine" in "color.txt" with "uboot" and put the output on the screen run:
BatchSubstitute.bat "Yellow Submarine" uboot color.txt
Or
type color.txt|BatchSubstitute.bat "Yellow Submarine" uboot

Optionally pipe the output into a new file, i.e.
BatchSubstitute.bat "Yellow Submarine" uboot color.txt>newfile.txt
Or
type color.txt|BatchSubstitute.bat "Yellow Submarine" uboot>newfile.txt

Note: Due to the nature of the FOR command and string substitution, the following known restrictions apply:
  • Lines starting with "]" character will end up empty
  • OldStr must not start with "*"
  • Lines must not contain any of the following characters within a quoted string: "&<>|^", as discussed in this post.
Script: Download: BatchSubstitute.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude - parses a File line by line and replaces a substring"
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
:$changed 20100115
:$source https://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo.
)
Script Output:
 DOS Script Output
C:>type BatchSubstitute.txt
!!! THIS TEST DOESN`T REPLACE ANYTHING, IT JUST MAKES SURE
!!! THE SCRIPT WORKS FOR SPECIAL CHARACTERS.
!!! THE SCRIPT WOULD NOT WORK IF ANY OF THE CHARACTERs &<>|^ WOULD
!!! APPEAR WITHIN A QUOTED STRING
Next line is empty

this > is a grater-than character
this < is a less-than character
this ( is a opening bracket character
this ) is a closing bracket character
this % is a percent character
this & is an ampersand character
this ! is an exclamation character
this " is a quote character
this | is a vertical character
this ^ is a up character
this is a "quoted string"
this is a %percented string%
this is a !exclamationed string!
a "quoted ( opening bracket"
a "quoted ) closing bracket"
a "quoted % quote character"
a "quoted ! quote character"
a "quoted " quote character"

C:>BatchSubstitute.bat Oldtext Newtext BatchSubstitute.txt
!!! THIS TEST DOESN`T REPLACE ANYTHING, IT JUST MAKES SURE
!!! THE SCRIPT WORKS FOR SPECIAL CHARACTERS.
!!! THE SCRIPT WOULD NOT WORK IF ANY OF THE CHARACTERs &<>|^ WOULD
!!! APPEAR WITHIN A QUOTED STRING
Next line is empty

this > is a grater-than character
this < is a less-than character
this ( is a opening bracket character
this ) is a closing bracket character
this % is a percent character
this & is an ampersand character
this ! is an exclamation character
this " is a quote character
this | is a vertical character
this ^ is a up character
this is a "quoted string"
this is a %percented string%
this is a !exclamationed string!
a "quoted ( opening bracket"
a "quoted ) closing bracket"
a "quoted % quote character"
a "quoted ! quote character"
a "quoted " quote character"

TOP
2010-04-18

DOS Batch - Force Delete All Print Jobs - Get rid of these pesky print jobs

Description:

Did you ever pull the paper out of your printer to stop it from printing? Then surly next thing you did was power cycling the printer to empty the printer buffer and then cancelling the print job from the printer spooler on your PC. The print job sometimes remains a long time in the printer queue before finally disappearing and allowing the next print job to be processed. This is annoying on my box it takes up to 5 minutes. Even rebooting the PC doesn`t help as it doesn`t empty the printer spooler.

This little batch gets it done. It temporarily stops the spooler service and removes all files from the printer queue. Beware though that all printer jobs will be deleted, not only the ones that got canceled.

Script: Download: BatchDeleteAllPrintJobs.bat  
1.
2.
3.
4.
5.
6.
7.
8.
@echo off
:$reference https://www.dostips.com/
:$reference https://support.microsoft.com/kb/946737
net stop spooler
del "%systemroot%\system32\spool\printers\*.shd"
del "%systemroot%\system32\spool\printers\*.spl"
net start spooler
pause

TOP
2008-03-29

DOS Batch - Progress - Show progress in batch using the title bar

Description: Showing progress in the output window seems impractical in DOS batch, since there is no way to overwrite a previews output for an updated progress status during each progress tick. Using the ECHO command is not nice, screen content quickly scrolls out of sight. A practicable alternative may be to use the window TITLE for the progress message. A nice side effect is that you can minimize the batch window and still observe the progress output in the task bar, since the task bar text will always reflect the window title text.
Script: Download: DosProgress.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
@ECHO OFF
set "max=11"
call :initProgress %max% "Window Title: [PPP]"
for /l %%N in (1,1,%max%) do (
    ping -n 2 -w 1 127.0.0.1>NUL
    call:doProgress
)
GOTO:EOF

:initProgress max format -- initialize an internal progress counter and display the progress in percent
::                       -- max    [in]     - progress counter maximum, equal to 100 percent
::                       -- format [in,opt] - title string formatter, default is '[P] completed.'
:$created 20060101 :$changed 20080327
:$source https://www.dostips.com
set /a "ProgressCnt=-1"
set /a "ProgressMax=%~1"
set "ProgressFormat=%~2"
if not defined ProgressFormat set "ProgressFormat=[PPPP]"
set "ProgressFormat=%ProgressFormat:[PPPP]=[P] completed.%"
call:doProgress
EXIT /b


:doProgress -- display the next progress tick
:$created 20060101 :$changed 20080327
:$source https://www.dostips.com
set /a "ProgressCnt+=1"
SETLOCAL ENABLEDELAYEDEXPANSION
set /a "per100=100*ProgressCnt/ProgressMax"
set /a "per10=per100/10"
set /a "per10m=10-per100/10-1"
set "P=%per100%%%"
set "PP="
for /l %%N in (0,1,%per10%) do call set "PP=%%PP%%*"
for /l %%N in (%per10%,1,9) do call set "PP=%%PP%% "
set "PPP="
for /l %%N in (0,1,%per10m%) do call set "PPP=%%PPP%%*"
set "ProgressFormat=%ProgressFormat:[P]=!P!%"
set "ProgressFormat=%ProgressFormat:[PP]=!PP!%"
set "ProgressFormat=%ProgressFormat:[PPP]=!PPP!%"
title %ProgressFormat%
EXIT /b
Output:

TOP
2008-11-13

DOS Batch - Quine 109 bytes - A pretty short DOS Batch Quine

Description: A Quine is a program whose only output is its program code.
Run the Quine using the following command in order to make sure Delayed Expansion is disabled and ECHO is OFF:
C:> Cmd /Q /V:Off /C BatchQuine.bat
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_1_3.bat  
1.
2.
3.
Set "T=Echo Set "T=!T!"&Call Echo Set E=!E!E!E!!E!E!E!&Echo Cmd/V:On/C"!E!T!E!""
Set E=%%
Cmd/V:On/C"%T%"
Script Output:
 DOS Script Output
Set "T=Echo Set "T=!T!"&Call Echo Set E=!E!E!E!!E!E!E!&Echo Cmd/V:On/C"!E!T!E!""
Set E=%%
Cmd/V:On/C"%T%"

TOP
2008-11-13

DOS Batch - Quine 134 bytes - A pretty short DOS Batch Quine

Description: A Quine is a program whose only output is its program code.
This little Quine has been developed by Peter Hartmann. Run the Quine using the following command in order to make sure Delayed Expansion is disabled and ECHO is OFF:
C:> Cmd /Q /V:Off /C BatchQuine.bat
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_2_2.bat  
1.
2.
3.
Set "T=Echo Set "T=!T!"&Echo Set "U=!U!""
Set "U=Echo Cmd/V:On/CCmd/V:On/C!T!&Cmd/V:On/C!U!"
Cmd/V:On/CCmd/V:On/C!T!&Cmd/V:On/C!U!
Script Output:
 DOS Script Output
Set "T=Echo Set "T=!T!"&Echo Set "U=!U!""
Set "U=Echo Cmd/V:On/CCmd/V:On/C!T!&Cmd/V:On/C!U!"
Cmd/V:On/CCmd/V:On/C!T!&Cmd/V:On/C!U!

TOP
2008-11-13

DOS Batch - Quine 159 bytes - A pretty short DOS Batch Quine

Description: A Quine is a program whose only output is its program code.
Run the Quine using the following command in order to make sure Delayed Expansion is disabled and ECHO is OFF:
C:> Cmd /Q /V:Off /C BatchQuine.bat
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_1_1_1.bat  
1.
2.
3.
4.
Set "T=Echo Set "T=!T!"&Call Echo Set "E=!E!E!E!!E!E!E!"&Echo Setlocal Enabledelayedexpansion&Echo !E!T!E!"
Set "E=%%"
Setlocal Enabledelayedexpansion
%T%
Script Output:
 DOS Script Output
Set "T=Echo Set "T=!T!"&Call Echo Set "E=!E!E!E!!E!E!E!"&Echo Setlocal Enabledelayedexpansion&Echo !E!T!E!"
Set "E=%%"
Setlocal Enabledelayedexpansion
%T%

TOP
2008-11-13

DOS Batch - Quine 259 bytes - A DOS Batch Quine that makes no assumption

Description: A Quine is a program whose only output is its program code.
This little Quine has been developed by Peter Hartmann.
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_1_2.bat  
1.
2.
3.
4.
5.
@Set "Src=www.Dostips.com"
@Setlocal Disabledelayedexpansion
@Set "T=Echo @Set "Src=www.Dostips.com"&Echo @Setlocal Disabledelayedexpansion&Echo @Set "T=!T!"&Call Echo @Set "E=!E!E!E!!E!E!E!"&Echo @Cmd /V:On /C "!E!T!E!""
@Set "E=%%"
@Cmd /V:On /C "%T%"
Script Output:
 DOS Script Output
@Set "Src=www.Dostips.com"
@Setlocal Disabledelayedexpansion
@Set "T=Echo @Set "Src=www.Dostips.com"&Echo @Setlocal Disabledelayedexpansion&Echo @Set "T=!T!"&Call Echo @Set "E=!E!E!E!!E!E!E!"&Echo @Cmd /V:On /C "!E!T!E!""
@Set "E=%%"
@Cmd /V:On /C "%T%"

TOP
2008-11-13

DOS Batch - Quine 301 bytes - A DOS Batch Quine that makes no assumption

Description: A Quine is a program whose only output is its program code.
This little Quine has been developed by Peter Hartmann.
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_1_1.bat  
1.
2.
3.
4.
5.
6.
@Set "Src=www.Dostips.com"
@Setlocal Disabledelayedexpansion
@Set "T=Echo @Set "Src=www.Dostips.com"&Echo @Setlocal Disabledelayedexpansion&Echo @Set "T=!T!"&Call Echo @Set "E=!E!E!E!!E!E!E!"&Echo @Setlocal Enabledelayedexpansion&Echo @!E!T!E!"
@Set "E=%%"
@Setlocal Enabledelayedexpansion
@%T%
Script Output:
 DOS Script Output
@Set "Src=www.Dostips.com"
@Setlocal Disabledelayedexpansion
@Set "T=Echo @Set "Src=www.Dostips.com"&Echo @Setlocal Disabledelayedexpansion&Echo @Set "T=!T!"&Call Echo @Set "E=!E!E!E!!E!E!E!"&Echo @Setlocal Enabledelayedexpansion&Echo @!E!T!E!"
@Set "E=%%"
@Setlocal Enabledelayedexpansion
@%T%

TOP
2008-11-13

DOS Batch - Quine 308 bytes - A DOS Batch Quine that makes no assumption

Description: A Quine is a program whose only output is its program code.
This little Quine has been developed by Peter Hartmann.
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_2_1.bat  
1.
2.
3.
4.
5.
6.
@Echo Off
Set "Src=www.Dostips.com"
Setlocal Disabledelayedexpansion
Set "T=Echo @Echo Off&Echo Set "Src=www.Dostips.com"&Echo Setlocal Disabledelayedexpansion&Echo Set "T=!T!"&Echo Set "U=!U!""
Set "U=Echo Cmd /V:On /C Cmd /V:On /C !T!&Cmd /V:On /C !U!"
Cmd /V:On /C Cmd /V:On /C !T!&Cmd /V:On /C !U!
Script Output:
 DOS Script Output
@Echo Off
Set "Src=www.Dostips.com"
Setlocal Disabledelayedexpansion
Set "T=Echo @Echo Off&Echo Set "Src=www.Dostips.com"&Echo Setlocal Disabledelayedexpansion&Echo Set "T=!T!"&Echo Set "U=!U!""
Set "U=Echo Cmd /V:On /C Cmd /V:On /C !T!&Cmd /V:On /C !U!"
Cmd /V:On /C Cmd /V:On /C !T!&Cmd /V:On /C !U!

TOP
2008-11-13

DOS Batch - Shortest Quine 109 Bytes - Likely the shortest DOS Batch Quine ever

Description: A Quine is a program whose only output is its program code.
Run the Quine using the following command in order to make sure Delayed Expansion is disabled and ECHO is OFF:
C:> Cmd /Q /V:Off /C BatchQuine.bat
If you use this code make sure to add a reference to DosTips.com.
Script: Download: BatchQuine_1_3.bat  
1.
2.
3.
Set "T=Echo Set "T=!T!"&Call Echo Set E=!E!E!E!!E!E!E!&Echo Cmd/V:On/C"!E!T!E!""
Set E=%%
Cmd/V:On/C"%T%"
Script Output:
 DOS Script Output
Set "T=Echo Set "T=!T!"&Call Echo Set E=!E!E!E!!E!E!E!&Echo Cmd/V:On/C"!E!T!E!""
Set E=%%
Cmd/V:On/C"%T%"

TOP
2008-01-01

DOS Batch - Simple Menu - Simple menu framework. Plug in a new menu item and coresponding script as single function block

Description:

This simple menu framework parses itself for batch labels of certain signature and lists them as menu items. The self-parsing feature makes the menu generic. New menu items can be inserted by adding new function blocks without changing the menu infrastructure.

Features:
  • simple and well structured
  • easy to enhance
  • easy to maintain
Script: Download: BatchMenu.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
@ECHO OFF
REM.-- Prepare the Command Processor
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

:menuLOOP
echo.
echo.= Menu =================================================
echo.
for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo.  %%B  %%C
set choice=
echo.&set /p choice=Make a choice or hit ENTER to quit: ||GOTO:EOF
echo.&call:menu_%choice%
GOTO:menuLOOP

::-----------------------------------------------------------
:: menu functions follow below here
::-----------------------------------------------------------

:menu_1   Have some fun
echo.Have some fun by adding some more code right here
GOTO:EOF

:menu_2   Get a water
echo.Get a water and then add some code right here
GOTO:EOF

:menu_

:menu_T   Tip
echo.It's easy to add a line separator using one or more fake labels
GOTO:EOF

:menu_C   Clear Screen
cls
GOTO:EOF
Script Output:
 DOS Script Output
= Menu =================================================

  1  Have some fun
  2  Get a water

  T  Tip
  C  Clear Screen

Make a choice or hit ENTER to quit:

TOP
2008-01-01

DOS Batch - Sorting text with numbers - Sorting that handles numbers as numbers not text

Description:

This batch sort`s text by handling the first number found in each line as real number not as text.

E.g.:
  • In a text search 10 is less than 9, because the first letter 1 is less than 9
  • In a number search 10 is greater than 9
Script: sortn.bat
Script Output:
 DOS Script Output
Abc9def
Abc10def

TOP
2008-01-01

DOS Function Template - A function template with all features of a true DOS function

Description: The function template can be used as starting point for a new function. Complete the template into a useful function like this:
  • Rename the function
  • Add proper description for the function and its arguments
  • Fill in the function body
  • Return desired values
Script: Download: BatchFunctionTmpl.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:myFunctionName    -- function description here
::                 -- %~1: argument description here
SETLOCAL
REM.--function body here
set LocalVar1=...
set LocalVar2=...
(ENDLOCAL & REM -- RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%LocalVar1%
    IF "%~2" NEQ "" SET %~2=%LocalVar2%
)
GOTO:EOF

TOP
2008-01-01

DOS Help File Builder - Command reference in HTML format via batch

Description:

A DOS batch that creates a well formatted HTML file listing the help output for all DOS commands.

Features:
  • Shows progress indication while creating the command reference
  • Outputs an command index with page links
  • Outputs the command help text for each DOS command documented by "C:>help /?"
Script: DosCommandIndex.bat
Script Output: DosCommandIndex.htm

TOP
2009-03-30

File age in days - Convert the file date into Julian Days to determine the age of a file age in days

Description:

Date and Time functions are useful for:

  • Calculations with date and time values
  • Determine the age of files in days
  • Determine the date difference in days

The example in this section demonstrates how to use the :ftime function to determine the age in days of all files in the temp directory.

Two variables are used

  • tnow - stores the current day in julian days format by calling :jdate
  • tfile - stores the file date in julian days format by calling :ftime

Using Delayed Expansion and exclamation marks around environment variables ensures that the `tfile`variable is substituted properly during each loop. Read more about this behavior in the SET command help (bottom half of the help text).

Script: Download: BatchFTime.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

cd /d "%temp%"

call:jdate tnow "%date%"
for %%F in (*.*) do (
    call:ftime tfile "%%F"
    set /a diff=tnow-tfile
    echo.%%~nxF is !diff! days old
)

ECHO.&PAUSE&GOTO:EOF


::-----------------------------------------------------------------------------------
::-- Functions start below here
::-----------------------------------------------------------------------------------


:ftime JD filename attr -- returns the file time in julian days
::                      -- JD    [out]    - valref file time in julian days
::                      -- attr  [in,opt] - time field to be used, creation/last-access/last-write, see 'dir /?', i.e. /tc, /ta, /tw, default is /tw
:$created 20060101 :$changed 20090322 :$categories DateAndTime
:$source https://www.dostips.com
SETLOCAL
set file=%~2
set attr=%~3
if not defined attr (call:jdate JD "- %~t2"
) ELSE (for /f %%a in ('"dir %attr% /-c "%file%"|findstr "^^[0-9]""') do call:jdate JD "%%a")
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" (SET %~1=%JD%) ELSE (echo.%JD%)
)
EXIT /b


:jdate JD DateStr -- converts a date string to julian day number with respect to regional date format
::                -- JD      [out,opt] - julian days
::                -- DateStr [in,opt]  - date string, e.g. "03/31/2006" or "Fri 03/31/2006" or "31.3.2006"
:$reference https://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20060101 :$changed 20080219
:$source https://www.dostips.com
SETLOCAL
set DateStr=%~2&if "%~2"=="" set DateStr=%date%
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
    for /f "tokens=1-3 delims=/.- " %%A in ("%DateStr:* =%") do (
        set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
set /a JD=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%JD%) ELSE (echo.%JD%)
EXIT /b
Script Output:
 DOS Script Output
00000002.ini is 42 days old
ActivePerlInstall.log is 39 days old
BatchJDate.bat is 0 days old
control.xml is 34 days old
debugf.txt is 26 days old
DFC5A2B2.TMP is 3 days old
EML30.tmp is 2 days old
EML39.tmp is 2 days old
EML3D.tmp is 2 days old
EXCEL.log is 20 days old
fdm9E1.tmp is 39 days old
gtb2C4.tmp is 62 days old
tmp.cab is 62 days old - gtb2
h2rC95.tmp is 36 days old
hpodvd09.log is 1 days old
hpzcoi00.log is 7 days old
hpzcoi01.log is 7 days old
hpzcoi02.log is 7 days old
hpzcoi03.log is 7 days old
IMT10.xml is 73 days old
IMT11.xml is 73 days old
IMT12.xml is 73 days old
IMT13.xml is 73 days old
IMT14.xml is 73 days old
IMT2B.xml is 73 days old
IMTF.xml is 73 days old
java_install_reg.log is 7 days old
jusched.log is 1 days old
LSBurnWatcher.log is 1 days old
msohdinh.tmp is 62 days old
patch.exe is 850 days old
patchw32.dll is 850 days old
r2hC94.tmp is 36 days old

Press any key to continue . . .

TOP
2009-12-06

FTP - Automatic Login - Automatically login to your FTP session with a single click

Description:

If you frequently find yourself calling FTP from the command line, each time having to login and change directory and change FTP modes, until you finally get where you want be in order to do some real work then you may wish to get there with a singe click.

This little batch can connect to your FTP server and logs you in before it gives you the prompt. You can easily add more FTP commands to it, like changing directories or switching to binary mode or whatever you like to be done before taking over control on the FTP prompt.

The FTP connection information is embedded within the batch itself. The batch connects to an FTP server by executing itself in FTP context using the FTP -s option. Once executing in FTP context it executes all FTP commands listed in the file. By omitting the final FTP "bye" command it will stop at the FTP prompt and wait for user input.

Optionally a FTP script can be provided as input stream, that way multiple FTP scripts can share the same login information. Example:

FtpLogin.bat <script1.ftp

Script: Download: FtpLogin.bat  
1.
2.
3.
4.
5.
@ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password
pwd
Script Output:
 DOS Script Output
ftp> @ftp -i -s:"%~f0"&GOTO:EOF
Invalid command.
ftp> open example.com
Connected to example.com.
220-
220 FTP Server ready
User (example.com:(none)):
331 Password required

230 User logged in
ftp> pwd
257 "/" is the current directory
ftp>

TOP
2010-02-05

FTP - Download Only New Files - Ftp script to download only files that don`t exist in local folder, i.e. to avoid overwrite

Description: This batch connects twice to the FTP server. First time it retrieves a list of files on the FTP server. This list is being trimmed to contain only files that don`t already exist locally. The files in the trimmed list are then downloaded during a second connection.

Note: Since all files are passed into the FTP`s MGET command there might be a limit to the number of files that can be processed at once.

Script: Download: BatchFtpDownloadOnlyNewFiles.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
@Echo Off

REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /C:".txt"

REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
    Call Set "FileList=%%FileList%% "%%A""
)

REM -- Extract Ftp Script to download files that don't exist in local folder
Set "FtpCommand=mget"
For %%A In (%FileList%) Do If Not Exist "%%~A" Call Set "FtpCommand=%%FtpCommand%% "%%~A""
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

For %%A In (%FtpCommand%) Do Echo.%%A

REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF


:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
::                  -- [IN]     StartMark - start mark, use '...:S' mark to allow variable substitution
::                  -- [IN,OPT] EndMark   - optional end mark, default is first empty line
::                  -- [IN,OPT] FileName  - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source https://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0&        rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
    if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
    if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
    if /i "%%B"=="%bmk%"   set "bExtr=Y"
    if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b


[Ftp Script 1]:S
!Title Connecting...
open example.com
username
password

!Title Preparing...
cd public_html/MyRemoteDirectory
lcd c:\MyLocalDirectory
binary
hash

!Title Processing... %FtpCommand%
%FtpCommand%

!Title Disconnecting...
disconnect
bye

TOP
2008-10-17

FTP - Resolving Environment Variables - Creating FTP script on the fly at runtime and using variables within the FTP script

Description:

This batch executed the FTP script embedded within the batch. All variables in the FTP script will be resolved.

The FOR loop extracts the FTP script into a temporary file. It the ECHO command is being CALLed for each line in order to resolve the variables.

Variables can be used within the FTP script the same way as in a batch script, including any string manipulation and command line arguments like %1 %2 %~n0 %* and so on.

All batch lines start with semicolon so that they will be ignored by the FOR loop. Semicolon is the default end-of-line (EOL) character used by the FOR command.

Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
;@echo off
;(for /f "usebackq delims=" %%A in ("%~f0") do call echo.%%A)>"%temp%\%~n0.ftp"
;ftp -i -s:"%temp%\%~n0.ftp"
;GOTO:EOF

open example.com
username
password
!:--- FTP commands below here ---
cd public_html/%COMPUTERNAME%
binary
hash on
%*
disconnect
bye

TOP
2008-01-01

FTP - Simple Single Batch - FTP script and batch in a single file

Description:

Embed FTP script into a batch script. Add this line at the beginning of the FTP script:

@ftp -i -s:"%~f0"&GOTO:EOF

The "FTP -s:ftpscript.txt" option executes a FTP script wheres "%~f0" resolved to the name of the running batch file. "GOTO:EOF" ends the batch script and makes sure the FTP script doesn`t run as part of the batch.
Good: You end up with only one file that contains the batch script and the FTP script combined.
Minor flaw: The batch command in the first line causes an "Invalid command." error when executed in FTP context, however the FTP execution will continue.

Features:
  • Single file to distribute combining batch and FTP script
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
@ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password
!:--- FTP commands below here ---
lcd c:\MyLocalDirectory
cd  public_html/MyRemoteDirectory
binary
mput "*.*"
disconnect
bye
Script Output:
 DOS Script Output
ftp> @ftp -i -s:"%~f0"&GOTO:EOF
Invalid command.
ftp> open example.com
User (Username:(none)):

ftp> !:--- FTP commands below here ---
ftp> lcd c:\MyLocalDirectory
Local directory now c:\MyLocalDirectory.
ftp> cd  public_html/MyRemoteDirectory
ftp> binary
ftp> !: mput "*.*"
ftp> disconnect
ftp> bye

TOP
2010-02-05

FTP - Upload Only New Files - Ftp script to upload only files that don`t exist in remote folder, i.e. incremental upload

Description: This batch connects twice to the FTP server. First time it retrieves a list of files on the FTP server. Local files that are are not in this list will then be uploaded during a second connection.

Note: Since all files are passed into the FTP`s MPUT command there might be a limit to the number of files that can be processed at once.

Script: Download: BatchFtpUploadOnlyNewFiles.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
@Echo Off
Setlocal Enabledelayedexpansion

REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /C:".txt"

REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
    Call Set "FileList=%%FileList%% "%%A""
)

REM -- Extract Ftp Script to upload files that don't exist in remote folder
Set "FtpCommand=mput"
For %%A In (%FileList%) Do set "Exist["%%~A"]=Y"
For /F "Delims=" %%A In ('"dir /b "%localdir%"|Findstr %FindStrArgs%"') Do (
    If Not defined Exist["%%~A"] Call Set "FtpCommand=%%FtpCommand%% "%%~A""
)
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
rem  Notepad "%temp%\%~n0.ftp"

For %%A In (%FtpCommand%) Do Echo.%%A

REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF


:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
::                  -- [IN]     StartMark - start mark, use '...:S' mark to allow variable substitution
::                  -- [IN,OPT] EndMark   - optional end mark, default is first empty line
::                  -- [IN,OPT] FileName  - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source https://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0&        rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
    if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
    if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
    if /i "%%B"=="%bmk%"   set "bExtr=Y"
    if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b


[Ftp Script 1]:S
!Title Connecting...
open example.com
username
password

!Title Preparing...
cd public_html/MyRemoteDirectory
lcd c:\MyLocalDirectory
binary
hash

!Title Processing... %FtpCommand%
%FtpCommand%

!Title Disconnecting...
disconnect
bye

TOP
2009-12-06

FTP Scripts Sharing Login Info - Manage the FTP login separately from your FTP scripts

Description:

If you have multiple FTP scripts that all use the same login information to your FTP site then you may wish to manage the login information separately from your FTP scripts in a single place. That way if the username, password or hostname for the FTP connection changes you only need to edit a single place instead of having to edit all FTP scripts one by one.

This automatic login script (also described in detail earlier) can be used to execute different FTP scripts that share the same login information stored within the batch file.

Example: FtpLogin.bat script1.ftp

Note: The FTP scripts passed into the batch must have the login sequence removed.

Note: The FTP script executes even if the connection sequence fails potentially causing `Not connected` and other errors. This is no different from regularly executing FTP with -s option.

Script: Download: FtpLoginSharing.bat  
1.
2.
3.
4.
@type %1|ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password

TOP
2008-01-01

OSQL.EXE - Run SQL script from DOS Batch - SQL script and dos batch script in one file, the One-File Solution

Description:

Embedding SQL script within a batch script is just as easy. The following batch script executes itself in SQL context. The trick is the GOTO command in the first line of the script. When executing GOTO START in batch context than the command processor will jump to the label ":START" and execute the batch script. The batch script will then run the OSQL.EXE using the batch file itself as SQL file argument to be executed. When subsequently executing the GOTO START line in SQL context, the query language processor will jump to the label "START:" and execute the SQL queries. In fact the file can be opened and executed in Query Analyzer as is, since the batch script in the file looks like a comment to the query language processor.

Script: Download: Batch4SQL.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
GOTO START
-- DOS jumps to the ':START' label
-- SQL jumps to the 'START:' label
-- Source https://www.dostips.com

/* Begin of SQL comment, this makes the BATCH script invisible for SQL
:: BATCH starts below here
:START
@echo off
CLS

OSQL.EXE -n -E -w 65536 -d NORTHWIND -i "%~f0"

PAUSE&GOTO:EOF
*/

-- SQL starts below here
START:
GO
SELECT * FROM AUTHOR
GO

TOP
2008-01-01

OSQL.EXE - Run SQL script from DOS Batch, passing parameters - Run SQL scripts with parameters passed in from the batch script

Description:

Now we can embed SQL queries into a batch file. But how can we pass arguments from the batch script into SQL? This can be done using a temporary table. Temporary tables live as long as the connection to the SQL Server. But how can we fill a temporary table with runtime data and execute the embedded SQL script without creating two separate SQL Server connections by calling OSQL.EXE twice? The trick is that OSQL allows to use the -i and -q option at the same time whereas:

  • -q specifies a query string to be executed
  • -i specifies a filename with SQL syntax to be executed
Both the query string and the SQL file will be executed using the same Server connection. Some testing shows that the query string -q will always be executed before the -I SQL file, which allows us to use a query string to set up a temporary table.

Script: Download: Batch4SQL2.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
GOTO START
-- DOS jumps to the ':START' label
-- SQL jumps to the 'START:' label
-- Source https://www.dostips.com

/* Begin of SQL comment, this makes the BATCH script invisible for SQL
:: BATCH starts below here
:START
@echo off
CLS

set /p AuthorName=Author Name:
set /p AuthorCity=Author City:

rem.-------------------------------------------------------------------------
rem.Execute THIS file in SQL context transmitting arguments per temp table
set Args=

rem.--BEGIN ARGS SECTION ------------------
set Args=%Args% INSERT #ArgsTable VALUES ('AuthorName','%AuthorName%')
set Args=%Args% INSERT #ArgsTable VALUES ('AuthorCity','%AuthorCity%')
rem.--END   ARGS SECTION ------------------

set Args= -q "SET NOCOUNT ON CREATE TABLE #ArgsTable(Arg char(16) PRIMARY KEY, Val char(32)) %Args%"

OSQL.EXE -n -E -w 65536 -d NORTHWIND %Args% -i "%~f0"

PAUSE&GOTO:EOF
*/

-- SQL starts below here
START:
GO

DECLARE @AuthorName varchar(128)
DECLARE @AuthorCity varchar(128)

--Set defaults for values as needed
SET @AuthorName = ''
SET @AuthorCity = ''

--Copy data from temporary table into variables
IF EXISTS (SELECT name, type FROM tempdb..sysobjects WHERE name like '#ArgsTable_%' AND type = 'U')
BEGIN
    SELECT @AuthorName=Val FROM #ArgsTable  WHERE Arg='AuthorName'
    SELECT @AuthorCity=Val FROM #ArgsTable  WHERE Arg='AuthorCity'
END

print @AuthorName
print @AuthorCity

GO

TOP
2008-01-01

Perl - Perl Script within a DOS Batch - Perl script and batch in a single file

Description:

It`s nice not to have to type "perl -s Batch4Parl.pl" into the command line and rather being able to just double click a Perl script in Explorer. The trick of renaming the Perl .pl to a batch .bat file and wrapping a batch script around the Perl script is well known under Perl monks. However the solution I have seen so far needed batch code before and after the Perl script where as the solution presented below only needs some lines of DOS at the top. The added DOS script is generic and works independent from the name of the file.

When running the batch the DOS command interpreter will read the first lines and execute the file itself in Perl context.

Script: Download: Batch4Perl.bat  
1.
2.
3.
4.
5.
@rem = 'source https://www.dostips.com
@CD/d"%~dp0"&perl -s "%~nx0" %*&Exit/b&:';

#perl script starts below here
print 'Hi there!  DOS rocks!\n'

TOP
2008-01-01

Perl Script within a DOS Batch with delayed exit - Perl script and batch in a single file

Description:

This example works just as the previews one but will wait 4 seconds before the application finally closes. This is just enough time to inspect the screen output before the window vanishes. The delay can probably be done much easier in Perl, but somebody just starting on Perl might find this still useful.

Script: Download: Batch4Perl2.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
@rem = 'Perl, ccperl will read this as an array of assignment & skip this block
@CD /d "%~dp0"
@perl -s "%~nx0" %*
@FOR /L %%c in (4,-1,1) do @(TITLE %~nx0 - %%cs to close & ping -n 2 -w 1000 127.0.0.1 >NUL)
@TITLE Press any key to close the window&ECHO.&GOTO:EOF
@rem ';

#perl script starts below here
print 'Hi there!  DOS rocks!\n'

TOP
2008-01-01

Simple Batch Template - Template with simple init and exit

Description: The function template can be used as starting point for a new batch.
Script: Download: BatchSimple.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
@ECHO OFF
REM.-- Prepare the Command Processor
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION


REM.-- your code goes here
echo.Hello World


REM.-- End of application
ECHO.&ECHO.Press any key to end the application.
PAUSE>NUL&GOTO:EOF


Ad: