출처: http://www.dostips.com/DtCodeBatchFiles.php

A collection of batch files.


Classic FTP
Executing a FTP script.

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

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

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

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

DOS Batch - FTP Scripts
File Transfer with FTP, One-File Solution.

DOS Batch - Interfacing non DOS Software
Embed other languages into your batch, like: Perl, SQL, FTP, ...

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

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

DOS Batch FTP - Simple
FTP script and batch in a single file.

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

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

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

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

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

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

Simple Batch Template
Template with simple init and exit.


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 Ouput
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:
Script Output:
 DOS Script Ouput
= 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 Ouput
FileSearch, type '-' to refresh lookup list: logoMed.gif

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

TOP
2008-01-01

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 "*"
Script:
Download: BatchSubstitute.bat 
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

::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,opt] - string to replace with, can be blank
::          File   [in,opt] - file to be parsed, leave blank for STDIN
if "%~1"=="" find /v "" %3&GOTO:EOF&rem  if OldStr omitted then leave output unchanged
for /f "tokens=1,* delims=]" %%a in ('"find /n /v "" %3"') do (
    set line="%%b"
    for /f "tokens=*" %%x in ('"echo.%%line:%~1=%~2%%"') do echo.%%~x
)

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:
Script Output:
 DOS Script Ouput
= 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:
Script Output:
 DOS Script Ouput
Abc9def
Abc10def

TOP
2008-01-01

DOS Batch FTP - Simple - 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 Ouput
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
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:
Script Output:

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.
GOTO START
-- DOS jumps to the ':START' label
-- SQL jumps to the 'START:' label

/* 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 http://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.
6.
7.
8.
@rem = 'Perl, ccperl will read this as an array of assignment & skip this block
@CD /d "%~dp0"
@perl -s "%~nx0" %*
@GOTO:EOF
@rem ';

#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
AND