Saturday, 12 May 2012

STARTING WITH DOS 


DOS - Arithmetic:

How to use SET /A for arithmetic in DOS



TOP
2009-12-03

:toDec - convert a hexadecimal number to decimal

Description: call:toDec hex dec
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:toDec hex dec -- convert a hexadecimal number to decimal
::             -- hex [in]      - hexadecimal number to convert
::             -- dec [out,opt] - variable to store the converted decimal number in
:$created 20091203 :$changed 20091203 :$categories Arithmetic,Encoding
:$source http://www.dostips.com
SETLOCAL
set /a dec=0x%~1
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%dec%) ELSE ECHO.%dec%
)
EXIT /b

TOP
2011-03-30

:toHex - convert a decimal number to hexadecimal, i.e. -20 to FFFFFFEC or 26 to 0000001A

Description: call:toHex dec hex
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
:toHex dec hex -- convert a decimal number to hexadecimal, i.e. -20 to FFFFFFEC or 26 to 0000001A
::             -- dec [in]      - decimal number to convert
::             -- hex [out,opt] - variable to store the converted hexadecimal number in
::Thanks to 'dbenham' dostips forum users who inspired to improve this function
:$created 20091203 :$changed 20110330 :$categories Arithmetic,Encoding
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set /a dec=%~1
set "hex="
set "map=0123456789ABCDEF"
for /L %%N in (1,1,8) do (
    set /a "d=dec&15,dec>>=4"
    for %%D in (!d!) do set "hex=!map:~%%D,1!!hex!"
)
rem !!!! REMOVE LEADING ZEROS by activating the next line, e.g. will return 1A instead of 0000001A
rem for /f "tokens=* delims=0" %%A in ("%hex%") do set "hex=%%A"&if not defined hex set "hex=0"
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%hex%) ELSE ECHO.%hex%
)
EXIT /b

TOP
2008-04-01

Floating Point Arithmetic - Working around the limitations of the command processor

Description: Floating point arithmetic can be achieved by moving the fractions into the integer. I.e. A floating point equitation using values with 3 digits after the dot can be calculated as follows:
Floating Point: 12.055 + 1.001 = 13.056
Integer:        12055 + 1001 = 13056
Script:
1.
2.
set /a y=12055 + 1001
echo.y = %y%
Script Output:
 DOS Script Ouput
y = 13056

TOP
2008-04-01

Large Integers - Working around the limitations of the command processor


TOP
2008-04-01

Percent - Basic Percent arithmetic


TOP
2008-04-01

SET /A - Basic Integer Arithmetic

Description: The SET /A command can be used for basic arithmetic.
You can write SET /a y=3*x or SET /a y=3*%x%. Both are correct. The command interpreter is smart enough to recognize variables within a formula.
Script:
1.
2.
3.
4.
5.
set /a x=20
set /a y=3*x
set /a y+=140
set /a y/=2
echo.y = %y%
Script Output:
 DOS Script Ouput
y = 100



DOS Batch - String Difference - Difference between strings using LCS algorism:

Description: Calulates the difference between two strings using the Longest Common Sequence algorism.
Hope I`ll have time to refactor this into a DOS function.
Script: Download: BatchStringDiff.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.
@ECHO OFF
REM See also http://en.wikipedia.org/wiki/Longest_common_subsequence_problem

set "x= XMJYAUZU"
set "y= MZJAWXU"

echo.String1=%x%
echo.String2=%y%

call:strUBound x
call:strUBound y
call:removeArr ar


SETLOCAL ENABLEDELAYEDEXPANSION
for /l %%I in (0,1,%x.len%) do set "ar[%%I][0]=0"
for /l %%J in (1,1,%y.len%) do set "ar[0][%%J]=0"
for /l %%I in (1,1,%x.len%) do (
    for /l %%J in (1,1,%y.len%) do (
        set /a "Ii=%%I-1"
        set /a "Jj=%%J-1"
        if "!x:~%%I,1!"=="!y:~%%J,1!" (
            call set /a "ar[%%I][%%J]=ar[!Ii!][!Jj!]+1"
        ) ELSE (
            call:max ar[%%I][%%J] ar[%%I][!Jj!] ar[!Ii!][%%J]
)   )   )

call:printDiff %x.len% %y.len% ar "%x%" "%y%"
call:dumpArr2 ar %x.len% %y.len%
pause
GOTO:EOF


:printDiff i, j, C[0..m,0..n], X[1..m], Y[1..n]
SETLOCAL ENABLEDELAYEDEXPANSION
set "I=%~1"
set "J=%~2"
set "ar=%~3"
set "x=%~4"
set "y=%~5"
set /a "Ii=I-1"
set /a "Jj=J-1"
set "else1=Y"
if %I% GTR 0 if %J% GTR 0 if "!x:~%I%,1!"=="!y:~%J%,1!" (
    set "else1="
    call:printDiff %Ii% %Jj% ar "%x%" "%y%"
    echo.= !x:~%I%,1!
)
if defined else1 (
    set "else2=Y"
    if %J% GTR 0 (
        set "or1="
        if %I%==0 set "or1=Y"
        if !%ar%[%I%][%Jj%]! GEQ !%ar%[%Ii%][%J%]! set "or1=Y"
        if defined or1 (
            set "else2="
            call:printDiff %I% %Jj% ar "%x%" "%y%"
            echo.+ !y:~%J%,1!
        )
    )
    if defined else2 (
        if %I% GTR 0 (
            set "or1="
            if %J%==0 set "or1=Y"
            if !%ar%[%I%][%Jj%]! LSS !%ar%[%Ii%][%J%]! set "or1=Y"
            if defined or1 (
                call:printDiff %Ii% %J% ar "%x%" "%y%"
                echo.- !x:~%I%,1!
            )
        )
    )
)
GOTO:EOF


:max retval refval1 refval2
SETLOCAL
set /a "a=%~2"
set /a "b=%~3"
if %a% LSS %b% set /a "a=b"
(ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%a%) ELSE ECHO.%a%)
GOTO:EOF


:strUBound refval -- returns the number of characters in a string
for /f "delims=:" %%A in ('"(call echo.%%%~1%%&echo.)|findstr /o "$""') do set /a "%~1.len=%%A-4"
GOTO:EOF


:removeArr arr -- remove an array
::             -- arr [in]  - array name
:$source http://www.dostips.com
for /f "delims==" %%a in ('"set %~1[ 2>NUL"') do set "%%a="
EXIT /b


:dumpArr2 arr i j -- dump array content, two dimensional
::                -- arr [in] - array name
::                -- i   [in] - size of first dimension
::                -- j   [in] - size of second dimension
:$source http://www.dostips.com
SETLOCAL
for /l %%I in (0,1,%2) do (
    set "ln="
    for /l %%J in (0,1,%3) do (
        call set "v=    %%%~1[%%I][%%J]%%"
        call set "ln=%%ln%%%%v:~-1%%"
    )
    call echo.%%ln%%
)
EXIT /b
Script Output:
 DOS Script Ouput
String1= XMJYAUZU
String2= MZJAWXU
- X
= M
+ Z
= J
- Y
= A
- U
- Z
+ W
+ X
= U
00000000
00000011
01111111
01122222
01122222
01123333
01123334
01223334
01223334
 
 

1        General


DOS batch files are written in plain text.  Any text editor that can store plain text can be used to create a new DOS batch file.
DOS batch files use the file extension .bat or .cmd.
In our simple example we will use Notepad to create a batch file right on the desktop.
The Notepad program is available on all Windows platforms.

2        Create a DOS batch - "hello.bat"

Description
Use Notepad to create a new file called hello.bat on your desktop.  Add the code shown below to the file and save it.
This can be done step by step as follows:
Do
·          In the Start menu click: Programs – Accessories – Notepad

The Notepad program starts up showing an empty document with the title: “Untitled - Notepad”
Do
·          In the Notepad menu click:  File – Save As

The Save As dialog shows up
Do
·          In the Save As dialog use the Save in drop down box to select: Desktop
·          In the File name field overwrite the file name by typing: hello.bat
·          Click: Save

The Save As dialog will close.  Notepad shows an empty document with the title: “hello.bat - Notepad”.  A new icon with the name hello.bat appears on the Desktop.
Do
·          Type or copy/paste the following code into notepad:
Code
@echo Hello world.
@pause
Do
·          In the Notepad menu choose: File - Save
Congrats
Done!  Your fist DOS batch file is ready to run.

3        Execute a DOS batch - "hello.bat"

Do
·          Minimize all windows and locate the icon called hello.bat on your desktop.
·          Double click the hello.bat icon

A new window will open showing the following message:

Hello world.
Press any key to continue . . .
Do
·          Press any key, e.g. Space

The window will close.
Congrats
You just executed your first DOS batch.

4        Summary


When double clicking hello.bat on the desktop the file was passed to the DOS command processor.  Independent from the executed batch file the command processor will always open a new window.  This window will close when the command processor finished executing the batch file.
The command processor executes the commands listed in the batch file line by line.  Commands in the batch file can instruct the command processor to interact with the user, i.e. to show some text output in the window or to wait fro keyboard input.
If not instructed differently the command processor echoes each command from the batch to the window before executing it.  This can be useful for testing and debugging but is usually annoying in the final version of the batch file and because of this omitted in the example by having the ‘@’ sign in front of each line.
Inside Hello.bat
The first line instructs the command processor to show the text: “Hello World.”
The second line instructs the command processor to pause till the user hits a key on the keyboard.
After pressing a key the batch file finishes and the command processor will close the window.
Lesson learned
The simple example teaches three features of the command processor.
·          The echo command displays text on the screen.
·          The pause command causes the command processor to pause until the user hits a key on the keyboard.
·          The ‘@’ sign at the beginning of a line prevents the command processor to echo the line on the screen while executing.
Tip
To turn off the echoing of commands for the whole batch file use the “@echo off” command as first command in the batch file.  The hello.bat example can be rewritten as follows in order to avoid an ‘@’ in front of each line:
Code
@echo off
echo Hello world.
pause

5        How to continue from here


Now you have your first DOS batch running and you may want to know what all you can use it for.
A whole group of predefined DOS commands is available with your operating system that can be used to enhance this simple example and make a useful application out of it.
To list all predefined dos commands open a command console and type help.
This can be done as follows:
Do
·          In the Start menu click: Run

The Run dialog box opens
Do
·          In the Open edit box type: cmd.exe

The command console opens reporting the windows version.  A blinking cursor shows up.
Do
·          Enter: help and hit the  Enter key

A list of predefined DOS commands with a brief description shows up.  Followed by the blinking curser waiting for more input.
Do
·          Pick any dos command from the list.  Type help and the DOS command to get more information about it’s usage.  I.e. type: help echo and hit Enter to get the details about the echo command
Example
C:\>help echo
Displays messages, or turns command-echoing on or off.

  ECHO [ON | OFF]
  ECHO [message]

Type ECHO without parameters to display the current echo setting.

C:\>
Lesson learned
There is a whole list of predefined DOS commands available.  Those DOS commands can be combined in a batch file in order to build a useful DOS batch application.



DOS - Powerful Enablers

Basic yet powerful features make DOS a quite interesting script language.

Description: One might say DOS is obsolete, other`s might just wonder why it`s still supported out-of-the-box in all Windows Operating Systems. This list of basic features may help understand.


TOP
2008-12-18

DOS Batch Coding Guidelines - Readability, consistency and maintainability

Description: This section is yet to be written.

TOP
2008-12-18

Reflection - A batch file can parse it`s own source script

Description: An executing DOS batch script is aware about the name and location of its own source file via the %0 batch parameter. This allows a batch to parse its own source file and change the execution path based on the parsing result. This is useful for e.g:
  • Storing configuration data or meta within the DOS batch and extract them file at runtime.
  • Storing data blocks within the DOS batch file and extract them at runtime.

TOP
2008-12-18

Self Modification - A batch file can modify itself

Description: A batch file that is executing can modify itself with immediate effect. As it executes it can build the next command to be executed and append the new command to itself. This is useful for e.g:
  • Creation and execution of DOS code on the fly where as the created code becomes permanent part of the batch file itself.
  • Allows writing adaptive DOS Batch files

TOP
2008-12-18

Variable Substitution - A variable substitutes a piece of command line

Description: In DOS a variable is simply a place holder for a piece of command line. At runtime a variable is simply being substituted by its string content. ThatĆ¢€™s why the string content can be a value, a command, partial value, a partial command or a mix of them. In case of substituting a variable to a command, this command to be substituted can use variables itself. This opens up a lot of space for creativity, e.g.:
  • Handling DOS code as data until execution
  • Creation and execution of temporary DOS code on the fly



TOP
2008-03-07

Initializing a batch - Commands that are typically executed at the beginning of a batch script

Description: At the beginning of a DOS batch file belongs the initialization of the command processor. This is to ensure subsequent DOS batch script will be handled by the command interpreter as we intended to. First let`s turn command-echoing off so that the output screen doesn`t get polluted with batch file content itself during execution. Second, in order to enable the great features of the command processor as required by most the other script code described here, the initialization code shall turn on Extensions and Delayed Expansion.
Script:
1.
2.
3.
4.
@echo off
REM.-- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

TOP
2008-03-07

Version History - Add a version history, track date, author and description of each change

Description: Having a version history within you DOS batch file is good practice in order to keep track of when changed what. Have the following code block close to the beginning of each batch file to present a nicely formatted version history. The version history can be updated by copying the last entry and modifying Date, Author, and Description appropriately.
Script:
1.
2.
3.
4.
5.
6.
::: -- Version History Ć¢€“-
:::          XX.XXX         YYYYMMDD Author Description
SET "version=01.000-beta" &:20051201 p.h.   initial version, providing the framework
SET "version=01.000"      &:20051202 p.h.   framework ready
SET "version=01.001"      &:20051203 p.h.   added cool new features
::: !! For a new version entry, copy the last entry down and modify Date, Author and Description

TOP
2008-03-07

Window Title - Change the Window Title

Description: Application name and version of you application seem to make just the right title for the application window. Let`s store the title into a variable that way it can be reused later in the batch script in case we use the window title temporary to display something else. The TITLE command will set the window title.
Script:
1.
2.
3.
::: -- Set the window title --
SET "title=%~nx0 - version %version%"
TITLE %title%

TOP
2008-03-07

Window Color - Change the Window Color

Description: The background and foreground color of a window can be changed using the COLOR command followed by two hexadecimal digits:
1st - background
2nd - foreground
The change will appear instantly for the whole window.
The color codes are:
    0 = Black       8 = Gray
    1 = Blue        9 = Light Blue
    2 = Green       A = Light Green
    3 = Aqua        B = Light Aqua
    4 = Red         C = Light Red
    5 = Purple      D = Light Purple
    6 = Yellow      E = Light Yellow
    7 = White       F = Bright White

Script:
1.
2.
::: -- Set the window color --
COLOR 1A

TOP
2008-03-07

Window Size - Change the Window Size

Description: To control the size of a window use the MODE command. The example shows how to size a window 90 characters horizontal and 10 lines vertical.
Script:
1.
2.
::: -- Set the window size --
MODE CON: COLS=90 LINES=10

TOP
2008-03-07

Exit - Exit on key pressed

Description: GOTO:EOF command will end a DOS batch application no matter whether subsequent code follow. Adding a PAUSE command will allow the user to inspect screen outputs before the application window disappears. Forcing an empty line via ECHO will nicely separate the "Press any key to continue" message created by the PAUSE command from any previous output.
Script:
1.
2.
::: -- End of application --
ECHO.&PAUSE&GOTO:EOF

TOP
2008-03-07

Exit - Exit on key pressed with customized message

Description: Letting the PAUSE command show the "Press any key to continue" message on exit may cause some confusion, since the application will finish and not continue. An ECHO command preceding the PAUSE command can be used to show a customize message. The text output of the PAUSE command can be omitted by piping its output into the NUL device.
Script:
1.
2.
::: -- End of application --
ECHO.&ECHO.Press any key to end the application.&PAUSE>NUL&GOTO:EOF

TOP
2008-03-07

Exit Delayed - Delayed exit without user interaction

Description: As you develop DOS batch files you may find it annoying to have to hit a key when the application finished just to close the window. You may want to have it close automatically but still being able to briefly scan over the execution result shown in the window.
A way to create a delay in a DOS batch program is to ping the localhost or 127.0.0.1. Sending 2 pings (ping Ć¢€“n 2 ...) will cause a delay of very close to one second. Invoking multiple pings as needed gives control about the delay time. Showing the remaining delay time in the window TITLE will even let the user know what`s going on.
I.e. replace the pause statement added earlier with the following code lines and run the application again. The menu will show a countdown of 5 seconds before closing the application. Changing the number 5 to 10 would result in a 10 second countdown.

What it`s good for:
  • Closing an application without user interaction
  • Leave enough time to view execution results
  • User can hit Pause on the keyboard to keep the window open
Script:
1.
2.
3.
::: -- 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-03-07

Echo a Blank Line - How to use ECHO to output a blank line

Description: To ouptut an empty line using the ECHO command simply append a dot to the command. Otherwise the ECHO command will show the current echo state. In fact it appears to be safe to always use the dot. A problem has been identified: "echo." stops working when there is a file named "echo" in the current directory. Using "echo/" instead may be a better option. See this forum post for details.
Script:
1.
2.
3.
4.
echo
echo This line is followed by an empty line.
              

Align Right - Align text to the right i.e. to improve readability of number columns

Description: Add leading spaces to a string to make sure the output lines up. I.e. for variables no longer than 8 characters add 8 spaces at the front and then show only the last 8 characters of the variable.
Script:
1.
2.
3.
4.
5.
6.
set x=3000
set y=2
set x=        %x%
set y=        %y%
echo.X=%x:~-8%
echo.Y=%y:~-8%
Script Output:
 DOS Script Ouput
X=    3000
Y=       2

TOP
2008-01-01

Left String - Extract characters from the beginning of a string

Description: Similar to the Left function in VB a batch script can return a specified number of characters from the left side of a string by specifying a substring for an expansion given a position of 0 and a length using :~ while expanding a variable content. The example shows how to return the first 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%
Script Output:
 DOS Script Ouput
politic
poli

TOP
2008-01-01

Map and Lookup - Use Key-Value pair list to lookup and translate values

Description: This example shows an approach to map a name of a month into it`s corresponding two digit number. The key-value pairs are listed in the map variable separated by semicolon. Key and value itself are separated by one dash character. Same can be used to tranlate a day-of-the-week short string into a day-of-the-week long string by changing the map content only.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
REM ---- Example 1: Translate name of month into two digit number ----
SET v=Mai

SET map=Jan-01;Feb-02;Mar-03;Apr-04;Mai-05;Jun-06;Jul-07;Aug-08;Sep-09;Oct-10;Nov-11;Dec-12
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

ECHO.%v%


REM ---- Example 2: Translate abbreviation into full string ----
SET v=sun

set map=mon-Monday;tue-Tuesday;wed-Wednesday;thu-Thursday;fri-Friday;sat-Saturday;sun-Sunday
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

  ECHO.%v%
Script Output:
 DOS Script Ouput
05
  Sunday

TOP
2008-01-01

Mid String - Extract a Substring by Position

Description: Similar to the Mid function in VB a batch script can return a specified number of characters from any position inside a string by specifying a substring for an expansion given a position and length using :~ while expanding a variable content. The example here shows how to extract the parts of a date.
Script:
1.
2.
3.
4.
5.
echo.Date   : %date%
echo.Weekday: %date:~0,3%
echo.Month  : %date:~4,2%
echo.Day    : %date:~7,2%
echo.Year   : %date:~10,4%
Script Output:
 DOS Script Ouput
Date   : Sat 03/11/2006
Weekday: Sat
Month  : 03
Day    : 11
Year   : 2006

TOP
2008-01-01

Remove - Remove a substring using string substitution

Description: The string substitution feature can also be used to remove a substring from another string. The example shown here removes all occurrences of "the " from the string variable str.
Script:
1.
2.
3.
4.
set str=the cat in the hat
echo.%str%
set str=%str:the =%
echo.%str%
Script Output:
 DOS Script Ouput
the cat in the hat
cat in hat

TOP
2008-01-01

Remove both Ends - Remove the first and the last character of a string

Description: Using :~1,-1 within a variable expansion will remove the first and last character of the string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~1,-1%
echo.%str%
Script Output:
 DOS Script Ouput
politic
oliti

TOP
2008-01-01

Remove Spaces - Remove all spaces in a string via substitution

Description: This script snippet can be used to remove all spaces from a string.
Script:
1.
2.
3.
4.
set str=      word       &rem
echo."%str%"
set str=%str: =%
echo."%str%"
Script Output:
 DOS Script Ouput
"      word       "
"word"

TOP
2008-01-01

Replace - Replace a substring using string substitution

Description: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences "teh" misspellings with "the" in the string variable str.
Script:
1.
2.
3.
4.
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%
Script Output:
 DOS Script Ouput
teh cat in teh hat
the cat in the hat

TOP
2008-01-01

Right String - Extract characters from the end of a string

Description: Similar to the Right function in VB a batch script can return a specified number of characters from the right side of a string by specifying a substring for an expansion given a negative position using :~ while expanding a variable content. The example shows how to return the last 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~-4%
echo.%str%
Script Output:
 DOS Script Ouput
politic
itic

TOP
2008-01-01

Split String - Split a String, Extract Substrings by Delimiters

Description: Use the FOR command to split a string into parts. The example shows how to split a date variable into its parts.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
echo.-- Split off the first date token, i.e. day of the week
for /f %%a in ("%date%") do set d=%%a
echo.Date   : %date%
echo.d      : %d%
echo.

echo.-- Split the date into weekday, month, day, and year, using slash and space as delimiters
for /f "tokens=1,2,3,4 delims=/ " %%a in ("%date%") do set wday=%%a&set month=%%b&set day=%%c&set year=%%d
echo.Weekday: %wday%
echo.Month  : %month%
echo.Day    : %day%
echo.Year   : %year%
Script Output:
 DOS Script Ouput
-- Split off the first date token, i.e. day of the week
Date   : Thu 12/02/2005
d      : Thu

-- Split the date into weekday, month, day, and year, using slash and space as delimiters
Weekday: Thu
Month  : 12
Day    : 02
Year   : 2005

TOP
2008-02-26

String Concatenation - Add one string to another string

Description: This example shows how to add two strings in DOS.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set "str1=Hello"
  set "str2=World"

  set "str3=%str1%%str2%"
  set "str4=%str1% %str2%"
  set "str1=%str1% DOS %str2%"

  echo.%str3%
  echo.%str4%
  echo.%str1%
Script Output:
 DOS Script Ouput
HelloWorld
  Hello World
  Hello DOS World

TOP
2008-04-28

Trim Left - Trim spaces from the beginning of a string via "FOR" command

Description: Use the FOR command to trim spaces at the beginning of a variable. In this example the variable to be trimmed is str.
Script:
1.
2.
3.
4.
set str=               15 Leading spaces to truncate
echo."%str%"
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
echo."%str%"
Script Output:
 DOS Script Ouput
"               15 Leading spaces to truncate"
"15 Leading spaces to truncate"

TOP
2008-01-01

Trim Quotes - Remove surrounding quotes via FOR command

Description: The FOR command can be used to safely remove quotes surrounding a string. If the string does not have quotes then it will remain unchanged.
Script:
1.
2.
3.
4.
set str="cmd politic"
echo.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str%
Script Output:
 DOS Script Ouput
"cmd politic"
cmd politic

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via "FOR" command

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use a FOR loop to trim up to 31 spaces from the end of a string. It assumes that Delayed Expansion is enabled.
Script:
1.
2.
3.
4.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
echo."%str%"
Script Output:
 DOS Script Ouput
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via substitution

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use the string substitution feature to trim up to 31 spaces from the end of a string. It assumes that the string to be trimmed never contains two hash "##" characters in a row.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
set str=%str%##
set str=%str:                ##=##%
set str=%str:        ##=##%
set str=%str:    ##=##%
set str=%str:  ##=##%
set str=%str: ##=##%
set str=%str:##=%
echo."%str%"
Script Output:
 DOS Script Ouput
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"

:lTrim - strips white spaces (or other characters) from the beginning of a string

Description: call:lTrim string char
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
:lTrim string char -- strips white spaces (or other characters) from the beginning of a string
::                 -- string [in,out] - string variable to be trimmed
::                 -- char   [in,opt] - character to be trimmed, default is space
:$created 20060101 :$changed 20080227 :$categories StringManipulation
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
call set "string=%%%~1%%"
set "charlist=%~2"
if not defined charlist set "charlist= "
for /f "tokens=* delims=%charlist%" %%a in ("%string%") do set "string=%%a"
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET "%~1=%string%"
)
EXIT /b

TOP
2008-02-19

:rTrim - strips white spaces (or other characters) from the end of a string

Description: call:rTrim string char max
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:rTrim string char max -- strips white spaces (or other characters) from the end of a string
::                     -- string [in,out] - string variable to be trimmed
::                     -- char   [in,opt] - character to be trimmed, default is space
::                     -- max    [in,opt] - maximum number of characters to be trimmed from the end, default is 32
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
call set string=%%%~1%%
set char=%~2
set max=%~3
if "%char%"=="" set char= &rem one space
if "%max%"=="" set max=32
for /l %%a in (1,1,%max%) do if "!string:~-1!"=="%char%" set string=!string:~0,-1!
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%string%
)
EXIT /b

TOP
2008-03-20

:StartsWith - Tests if a text starts with a given string

Description: call:StartsWith text string
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:StartsWith text string -- Tests if a text starts with a given string
::                      -- [IN] text   - text to be searched
::                      -- [IN] string - string to be tested for
:$created 20080320 :$changed 20080320 :$categories StringOperation,Condition
:$source http://www.dostips.com
SETLOCAL
set "txt=%~1"
set "str=%~2"
if defined str call set "s=%str%%%txt:*%str%=%%"
if /i "%txt%" NEQ "%s%" set=2>NUL
EXIT /b

TOP
2010-11-16

:strLen - returns the length of a string

Description: call:strLen string len
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
:strLen string len -- returns the length of a string
::                 -- string [in]  - variable name containing the string being measured for length
::                 -- len    [out] - variable to be used to return the string length
:: Many thanks to 'sowgtsoi', but also 'jeb' and 'amel27' dostips forum users helped making this short and efficient
:$created 20081122 :$changed 20101116 :$categories StringOperation
:$source http://www.dostips.com
(   SETLOCAL ENABLEDELAYEDEXPANSION
    set "str=A!%~1!"&rem keep the A up front to ensure we get the length and not the upper bound
                     rem it also avoids trouble in case of empty string
    set "len=0"
    for /L %%A in (12,-1,0) do (
        set /a "len|=1<<%%A"
        for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"
    )
)
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" SET /a %~2=%len%
)
EXIT /b

TOP
2008-02-19

:toCamelCase - converts a string to camel case

Description: call:toCamelCase str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
:toCamelCase str -- converts a string to camel case
::               -- str [in,out] - valref of string variable to be converted
:$created 20080219 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
REM make all lower case
for %%a in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i"
            "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r"
            "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z"
            "Ƅ=Ƥ" "Ɩ=ƶ" "Ɯ=Ć¼") do (
    call set "%~1=%%%~1:%%~a%%"
)
call set "%~1= %%%~1%%"
REM make first character upper case
for %%a in (" a=A" " b=B" " c=C" " d=D" " e=E" " f=F" " g=G" " h=H" " i=I"
            " j=J" " k=K" " l=L" " m=M" " n=N" " o=O" " p=P" " q=Q" " r=R"
            " s=S" " t=T" " u=U" " v=V" " w=W" " x=X" " y=Y" " z=Z"
            " Ć¤=Ƅ" " Ć¶=Ɩ" " Ć¼=Ɯ") do (
    call set "%~1=%%%~1:%%~a%%"
)
call set "%~1=%%%~1: =%%"
EXIT /b

TOP
2008-02-19

:toLower - converts uppercase character to lowercase

Description: call:toLower str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:toLower str -- converts uppercase character to lowercase
::           -- str [in,out] - valref of string variable to be converted
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
for %%a in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i"
            "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r"
            "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z" "Ƅ=Ƥ"
            "Ɩ=ƶ" "Ɯ=Ć¼") do (
    call set %~1=%%%~1:%%~a%%
)
EXIT /b

TOP
2008-02-19

:toUpper - converts lowercase character to uppercase

Description: call:toUpper str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:toUpper str -- converts lowercase character to uppercase
::           -- str [in,out] - valref of string variable to be converted
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
for %%a in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I"
            "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R"
            "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z" "Ƥ=Ƅ"
            "ƶ=Ɩ" "Ć¼=Ɯ") do (
    call set %~1=%%%~1:%%~a%%
)
EXIT /b

TOP
2008-02-19

:Trim - strip white spaces (or other characters) from the beginning and end of a string

Description: call:Trim string char max
Dependencies: :lTrim, :rTrim
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
:Trim string char max -- strip white spaces (or other characters) from the beginning and end of a string
::                    -- string [in,out] - string variable to be trimmed
::                    -- char   [in,opt] - character to be trimmed, default is space
::                    -- max    [in,opt] - maximum number of characters to be trimmed from the end, default is 32
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
call:lTrim "%~1" "%~2"
call:rTrim "%~1" "%~2" "%~3"
EXIT /b

TOP
2008-02-23

:trimSpaces - trims spaces around string variable

Description: call:trimSpaces varref
Dependencies: :trimSpaces2
Script:
1.
2.
3.
4.
5.
6.
:trimSpaces varref -- trims spaces around string variable
::                 -- varref [in,out] - variable to be trimmed
:$created 20060101 :$changed 20080223 :$categories StringManipulation
:$source http://www.dostips.com
call call:trimSpaces2 %~1 %%%~1%%
EXIT /b

TOP
2008-02-19

:trimSpaces2 - trims spaces around string and assigns result to variable

Description: call:trimSpaces2 retval string
Script:
1.
2.
3.
4.
5.
6.
7.
:trimSpaces2 retval string -- trims spaces around string and assigns result to variable
::                         -- retvar [out] variable name to store the result in
::                         -- string [in]  string to trim, must not be in quotes
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
for /f "tokens=1*" %%A in ("%*") do set "%%A=%%B"
EXIT /b

TOP
2008-02-19

:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc

Description: call:Unique ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
::          -- ret    [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
    for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
        set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b

TOP
2008-01-01

Align Right - Align text to the right i.e. to improve readability of number columns

Description: Add leading spaces to a string to make sure the output lines up. I.e. for variables no longer than 8 characters add 8 spaces at the front and then show only the last 8 characters of the variable.
Script:
1.
2.
3.
4.
5.
6.
set x=3000
set y=2
set x=        %x%
set y=        %y%
echo.X=%x:~-8%
echo.Y=%y:~-8%
Script Output:
 DOS Script Ouput
X=    3000
Y=       2

TOP
2008-01-01

Left String - Extract characters from the beginning of a string

Description: Similar to the Left function in VB a batch script can return a specified number of characters from the left side of a string by specifying a substring for an expansion given a position of 0 and a length using :~ while expanding a variable content. The example shows how to return the first 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%
Script Output:
 DOS Script Ouput
politic
poli

TOP
2008-01-01

Map and Lookup - Use Key-Value pair list to lookup and translate values

Description: This example shows an approach to map a name of a month into it`s corresponding two digit number. The key-value pairs are listed in the map variable separated by semicolon. Key and value itself are separated by one dash character. Same can be used to tranlate a day-of-the-week short string into a day-of-the-week long string by changing the map content only.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
REM ---- Example 1: Translate name of month into two digit number ----
SET v=Mai

SET map=Jan-01;Feb-02;Mar-03;Apr-04;Mai-05;Jun-06;Jul-07;Aug-08;Sep-09;Oct-10;Nov-11;Dec-12
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

ECHO.%v%


REM ---- Example 2: Translate abbreviation into full string ----
SET v=sun

set map=mon-Monday;tue-Tuesday;wed-Wednesday;thu-Thursday;fri-Friday;sat-Saturday;sun-Sunday
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

  ECHO.%v%
Script Output:
 DOS Script Ouput
05
  Sunday

TOP
2008-01-01

Mid String - Extract a Substring by Position

Description: Similar to the Mid function in VB a batch script can return a specified number of characters from any position inside a string by specifying a substring for an expansion given a position and length using :~ while expanding a variable content. The example here shows how to extract the parts of a date.
Script:
1.
2.
3.
4.
5.
echo.Date   : %date%
echo.Weekday: %date:~0,3%
echo.Month  : %date:~4,2%
echo.Day    : %date:~7,2%
echo.Year   : %date:~10,4%
Script Output:
 DOS Script Ouput
Date   : Sat 03/11/2006
Weekday: Sat
Month  : 03
Day    : 11
Year   : 2006

TOP
2008-01-01

Remove - Remove a substring using string substitution

Description: The string substitution feature can also be used to remove a substring from another string. The example shown here removes all occurrences of "the " from the string variable str.
Script:
1.
2.
3.
4.
set str=the cat in the hat
echo.%str%
set str=%str:the =%
echo.%str%
Script Output:
 DOS Script Ouput
the cat in the hat
cat in hat

TOP
2008-01-01

Remove both Ends - Remove the first and the last character of a string

Description: Using :~1,-1 within a variable expansion will remove the first and last character of the string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~1,-1%
echo.%str%
Script Output:
 DOS Script Ouput
politic
oliti

TOP
2008-01-01

Remove Spaces - Remove all spaces in a string via substitution

Description: This script snippet can be used to remove all spaces from a string.
Script:
1.
2.
3.
4.
set str=      word       &rem
echo."%str%"
set str=%str: =%
echo."%str%"
Script Output:
 DOS Script Ouput
"      word       "
"word"

TOP
2008-01-01

Replace - Replace a substring using string substitution

Description: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences "teh" misspellings with "the" in the string variable str.
Script:
1.
2.
3.
4.
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%
Script Output:
 DOS Script Ouput
teh cat in teh hat
the cat in the hat

TOP
2008-01-01

Right String - Extract characters from the end of a string

Description: Similar to the Right function in VB a batch script can return a specified number of characters from the right side of a string by specifying a substring for an expansion given a negative position using :~ while expanding a variable content. The example shows how to return the last 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~-4%
echo.%str%
Script Output:
 DOS Script Ouput
politic
itic

TOP
2008-01-01

Split String - Split a String, Extract Substrings by Delimiters

Description: Use the FOR command to split a string into parts. The example shows how to split a date variable into its parts.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
echo.-- Split off the first date token, i.e. day of the week
for /f %%a in ("%date%") do set d=%%a
echo.Date   : %date%
echo.d      : %d%
echo.

echo.-- Split the date into weekday, month, day, and year, using slash and space as delimiters
for /f "tokens=1,2,3,4 delims=/ " %%a in ("%date%") do set wday=%%a&set month=%%b&set day=%%c&set year=%%d
echo.Weekday: %wday%
echo.Month  : %month%
echo.Day    : %day%
echo.Year   : %year%
Script Output:
 DOS Script Ouput
-- Split off the first date token, i.e. day of the week
Date   : Thu 12/02/2005
d      : Thu

-- Split the date into weekday, month, day, and year, using slash and space as delimiters
Weekday: Thu
Month  : 12
Day    : 02
Year   : 2005

TOP
2008-02-26

String Concatenation - Add one string to another string

Description: This example shows how to add two strings in DOS.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set "str1=Hello"
  set "str2=World"

  set "str3=%str1%%str2%"
  set "str4=%str1% %str2%"
  set "str1=%str1% DOS %str2%"

  echo.%str3%
  echo.%str4%
  echo.%str1%
Script Output:
 DOS Script Ouput
HelloWorld
  Hello World
  Hello DOS World

TOP
2008-04-28

Trim Left - Trim spaces from the beginning of a string via "FOR" command

Description: Use the FOR command to trim spaces at the beginning of a variable. In this example the variable to be trimmed is str.
Script:
1.
2.
3.
4.
set str=               15 Leading spaces to truncate
echo."%str%"
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
echo."%str%"
Script Output:
 DOS Script Ouput
"               15 Leading spaces to truncate"
"15 Leading spaces to truncate"

TOP
2008-01-01

Trim Quotes - Remove surrounding quotes via FOR command

Description: The FOR command can be used to safely remove quotes surrounding a string. If the string does not have quotes then it will remain unchanged.
Script:
1.
2.
3.
4.
set str="cmd politic"
echo.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str%
Script Output:
 DOS Script Ouput
"cmd politic"
cmd politic

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via "FOR" command

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use a FOR loop to trim up to 31 spaces from the end of a string. It assumes that Delayed Expansion is enabled.
Script:
1.
2.
3.
4.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
echo."%str%"
Script Output:
 DOS Script Ouput
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via substitution

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use the string substitution feature to trim up to 31 spaces from the end of a string. It assumes that the string to be trimmed never contains two hash "##" characters in a row.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
set str=%str%##
set str=%str:                ##=##%
set str=%str:        ##=##%
set str=%str:    ##=##%
set str=%str:  ##=##%
set str=%str: ##=##%
set str=%str:##=%
echo."%str%"
Script Output:
 DOS Script Ouput
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"

1        Copy new and newer files only

Description
XCOPY’s /D option makes sure that only new and newer files will be copied.
source can be a file mask e.g.: *.*, my*.*, my*.log, directory\*.*
destination can be a directory e.g.: ., directory
Code
xcopy "%source%" "%destination%" /D /Y

2        Copy newer files only, destination must exist

Description
XCOPY’s /U option makes sure that files will only be copied as part of an update.
source can be a file mask e.g.: *.*, my*.*, my*.log, directory\*.*
destination can be a directory e.g.: ., directory
Code
xcopy "%source%" "%destination%" /D /U /Y

3        Copy new files only

Description
XCOPY’s /L option will not perform the actual copy but will list the files that would be copied without the /L option.  The resulting file list can be used to perform further checks before the actual copy.  In this example a FOR command parses the resulting file list and runs an additional if not exist check in order to make sure that no file gets overwritten.
source can be a file mask e.g.: *.*, my*.*, my*.log, directory\*.*
destination can be a directory e.g.: ., directory
Code
for /f %%a in ('xcopy "%source%" "%destination%" /L /Y') do (
    if not exist "%destination%.\%%~nxa" xcopy "%%a" "%destination%" /Y
)

4        Additional Task for each File to be copied

Description
Having the ability to retrieve a list of files that would be copied without actually performing the copy allows executing additional tasks for each file listed.  Performing the copy itself becomes optional.
The example shown here outputs a nice message for each file being copied and removes all text file from the destination folder that have the same name as the file to be copied but the extension .txt.
source can be a file mask e.g.: *.*, my*.*, my*.log, directory\*.*
destination can be a directory e.g.: ., directory
Code
for /f %%a in ('xcopy "%source%" "%destination%" /L /Y') do (
    echo.Copying file '%%a' and removing corresponding .txt files
    if exist %%~dpna.txt del %%~dpna.txt
    xcopy "%%a" "%destination%" /Y
)

5        Preserving the Directory Structure during Copy

Description
To copy files for backup purpose it is often necessarily to preserve the directory structure in the backup location.  I.e. In order to backup all *.pst files under the “c:\Documents and Settings” directory and copy them to “c:\pstbackup\ Documents and Settings\...” the code shown here can be used.
Note: You may think that a simple “xcopy "C:\Documents and Settings\*.pst" "c:\pstbackup\" /Y/U/S” does the job, but testing showed that it will always returns ”File not found - *.pst”.  So here a solution that does work:
Code
set sourcedir=c:\Documents and Settings\*.pst
set backupdir=c:\pstbackup
for /f "tokens=*" %%a in ('dir "%sourcedir%" /s/b') do (
    xcopy "%%a" "%backupdir%.%%~pa" /Y/U
)

6        Test for Open File

Description
The copy command can be used to check wither a file is open without modifying it.

How it works:
copy /-y will causes prompting to confirm you want to overwrite the file.
echo.N will abort the copy operation so that the copy really only checks whether the file is open.
>NUL will make sure everything happens quietly without showing anything on the screen.

If the file (to be copied) is not open then the copy operation will be successfully aborted by piping the 'N' into the conformation. Since such abort indicates success, the code behind the && will be executed.

If the file is open then the copy operation will fail and the code behind the || will be executed.
Code
echo.N|copy /-y NUL "%filename%">NUL&&(
    echo.%filename% is free!
    rem leave this rem here at the block end!!!
) || (
    echo.%filename% is in use!

 

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 http://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 http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20060101 :$changed 20080219
:$source http://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 Ouput
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
2008-02-19

:DeleteIfOld - deletes file or directory if older than given number of days

Description: call:DeleteIfOld name days tnow
Dependencies: :ftime
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
:DeleteIfOld name days tnow -- deletes file or directory if older than given number of days
::                          -- name [in] - name of file or directory
::                          -- days [in] - number of days to expire
::                          -- tnow [in] - today's date in julia days
:$created 20060101 :$changed 20080219 :$categories DateAndTime,FileOperation
:$source www.DosTips.com
SETLOCAL
set "days=%~2"
set "tnow=%~3"
call:ftime tfile "%~1"
set /a "diff=tnow-tfile"
if %diff% LEQ %days% EXIT /b
set "attr=%~a1"
rem ECHO.%attr%, %attr:~0,1%, %~nx1 is %diff% days old
if /i "%attr:~0,1%"=="d" (
    rd /Q /S "%~1"
) ELSE (
    del /Q "%~1"
)
EXIT /b

TOP
2009-03-22

:ftime - returns the file time in julian days

Description: call:ftime JD filename attr
Dependencies: :jdate
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
: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 http://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

TOP
2008-02-19

:date2jdate - converts a gregorian calender date to julian day format

Description: call:date2jdate JD YYYY MM DD
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
:date2jdate JD YYYY MM DD -- converts a gregorian calender date to julian day format
::                        -- JD   [out] - julian days
::                        -- YYYY [in]  - gregorian year, i.e. 2006
::                        -- MM   [in]  - gregorian month, i.e. 12 for december
::                        -- DD   [in]  - gregorian day, i.e. 31
:$reference http://aa.usno.navy.mil/faq/docs/JD_Formula.html
:$created 20060101 :$changed 20080219 :$categories DateAndTime
:$source http://www.dostips.com
SETLOCAL
set "yy=%~2"&set "mm=%~3"&set "dd=%~4"
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
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

TOP
2009-03-28

:jdate - converts a date string to julian day number with respect to regional date format

Description: call:jdate JD DateStr
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
: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 http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20060101 :$changed 20090328 :$categories DateAndTime
:$source http://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"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
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

TOP
2008-02-19

:jdate2date - converts julian days to gregorian date format

Description: call:jdate2date JD YYYY MM DD
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
:jdate2date JD YYYY MM DD -- converts julian days to gregorian date format
::                     -- JD   [in]  - julian days
::                     -- YYYY [out] - gregorian year, i.e. 2006
::                     -- MM   [out] - gregorian month, i.e. 12 for december
::                     -- DD   [out] - gregorian day, i.e. 31
:$reference http://aa.usno.navy.mil/faq/docs/JD_Formula.html
:$created 20060101 :$changed 20080219 :$categories DateAndTime
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set /a L= %~1+68569,     N= 4*L/146097, L= L-(146097*N+3)/4, I= 4000*(L+1)/1461001
set /a L= L-1461*I/4+31, J= 80*L/2447,  K= L-2447*J/80,      L= J/11
set /a J= J+2-12*L,      I= 100*(N-49)+I+L
set /a YYYY= I,  MM=100+J,  DD=100+K
set MM=%MM:~-2%
set DD=%DD:~-2%
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%YYYY%) ELSE echo.%YYYY%
    IF "%~3" NEQ "" (SET %~3=%MM%) ELSE echo.%MM%
    IF "%~4" NEQ "" (SET %~4=%DD%) ELSE echo.%DD%
)
EXIT /b

TOP
2008-06-12

:dayOfYear - returns the day of the year, i.e. 1 for 1/1/2008, 266 for 12/31/2008

Description: call:dayOfYear JD DateStr
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:dayOfYear JD DateStr -- returns the day of the year, i.e. 1 for 1/1/2008, 266 for 12/31/2008
::                    -- day     [out,opt] - variable name to store resulting day of the year
::                    -- DateStr [in,opt]  - date string, e.g. "3/31/2006" or "Fri 03/31/2006" or "31.3.2006", or omit form current date
:$reference http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20080612 :$changed 20080612 :$categories DateAndTime
:$source http://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
set /a "yy=10000%yy% %%10000,mm=1,dd=1"
set /a JD-=-1+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

TOP
2008-02-19

:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc

Description: call:Unique ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
::          -- ret    [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
    for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
        set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b

TOP
2008-02-19

:CmpFTime - compares the time of two files, succeeds if condition is met, fails otherwise

Description: call:CmpFTime op file1 file2 attr1 attr2
Script:
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.
:CmpFTime op file1 file2 attr1 attr2 -- compares the time of two files, succeeds if condition is met, fails otherwise
::                  -- op    [in]     - compare operator, see 'IF /?', i.e.EQU, NEQ, LSS, LEQ, GTR, GEQ
::                  -- fileL [in]     - file name, left side of comparisation
::                  -- file2 [in]     - file name, right side of comparisation
::                  -- attrL [in,opt] - time field to be used for fileL, see 'dir /?', i.e. /tc, /ta, /tw, default is /tw
::                  -- attrR [in,opt] - time field to be used for fileR, default is attrL
:$created 20060101 :$changed 20080219 :$categories DateAndTime,FileOperation
:$source http://www.dostips.com
SETLOCAL
set op=%~1
set fileL=%~2
set fileR=%~3
set attrL=%~4
set attrR=%~5
if "%op%"=="" set op===
if "%attrL%"=="" set attrL=/tw
if "%attrR%"=="" set attrR=%attrL%
for /f "tokens=1-6 delims=/: " %%a in ('"dir %attrL% /-c "%fileL%"|findstr "^^[0-1]""') do (
    set TL=%%c%%a%%b%%f%%d%%e
)
for /f "tokens=1-6 delims=/: " %%a in ('"dir %attrR% /-c "%fileR%"|findstr "^^[0-1]""') do (
    set TR=%%c%%a%%b%%f%%d%%e
)
if "%TL%" %op% "%TR%" (rem.) ELSE set=2>NUL
EXIT /b  
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).
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 http://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 http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20060101 :$changed 20080219
:$source http://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 Ouput
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
2008-02-19
:DeleteIfOld - deletes file or directory if older than given number of days
Description:
call:DeleteIfOld name days tnow
Dependencies:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
:DeleteIfOld name days tnow -- deletes file or directory if older than given number of days
::                          -- name [in] - name of file or directory
::                          -- days [in] - number of days to expire
::                          -- tnow [in] - today's date in julia days
:$created 20060101 :$changed 20080219 :$categories DateAndTime,FileOperation
:$source www.DosTips.com
SETLOCAL
set "days=%~2"
set "tnow=%~3"
call:ftime tfile "%~1"
set /a "diff=tnow-tfile"
if %diff% LEQ %days% EXIT /b
set "attr=%~a1"
rem ECHO.%attr%, %attr:~0,1%, %~nx1 is %diff% days old
if /i "%attr:~0,1%"=="d" (
    rd /Q /S "%~1"
) ELSE (
    del /Q "%~1"
)
EXIT /b

TOP
2009-03-22
:ftime - returns the file time in julian days
Description:
call:ftime JD filename attr
Dependencies:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
: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 http://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

TOP
2008-02-19
:date2jdate - converts a gregorian calender date to julian day format
Description:
call:date2jdate JD YYYY MM DD
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
:date2jdate JD YYYY MM DD -- converts a gregorian calender date to julian day format
::                        -- JD   [out] - julian days
::                        -- YYYY [in]  - gregorian year, i.e. 2006
::                        -- MM   [in]  - gregorian month, i.e. 12 for december
::                        -- DD   [in]  - gregorian day, i.e. 31
:$reference http://aa.usno.navy.mil/faq/docs/JD_Formula.html
:$created 20060101 :$changed 20080219 :$categories DateAndTime
:$source http://www.dostips.com
SETLOCAL
set "yy=%~2"&set "mm=%~3"&set "dd=%~4"
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
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

TOP
2009-03-28
:jdate - converts a date string to julian day number with respect to regional date format
Description:
call:jdate JD DateStr
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
: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 http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20060101 :$changed 20090328 :$categories DateAndTime
:$source http://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"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
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

TOP
2008-02-19
:jdate2date - converts julian days to gregorian date format
Description:
call:jdate2date JD YYYY MM DD
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
:jdate2date JD YYYY MM DD -- converts julian days to gregorian date format
::                     -- JD   [in]  - julian days
::                     -- YYYY [out] - gregorian year, i.e. 2006
::                     -- MM   [out] - gregorian month, i.e. 12 for december
::                     -- DD   [out] - gregorian day, i.e. 31
:$reference http://aa.usno.navy.mil/faq/docs/JD_Formula.html
:$created 20060101 :$changed 20080219 :$categories DateAndTime
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set /a L= %~1+68569,     N= 4*L/146097, L= L-(146097*N+3)/4, I= 4000*(L+1)/1461001
set /a L= L-1461*I/4+31, J= 80*L/2447,  K= L-2447*J/80,      L= J/11
set /a J= J+2-12*L,      I= 100*(N-49)+I+L
set /a YYYY= I,  MM=100+J,  DD=100+K
set MM=%MM:~-2%
set DD=%DD:~-2%
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%YYYY%) ELSE echo.%YYYY%
    IF "%~3" NEQ "" (SET %~3=%MM%) ELSE echo.%MM%
    IF "%~4" NEQ "" (SET %~4=%DD%) ELSE echo.%DD%
)
EXIT /b

TOP
2008-06-12
:dayOfYear - returns the day of the year, i.e. 1 for 1/1/2008, 266 for 12/31/2008
Description:
call:dayOfYear JD DateStr
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:dayOfYear JD DateStr -- returns the day of the year, i.e. 1 for 1/1/2008, 266 for 12/31/2008
::                    -- day     [out,opt] - variable name to store resulting day of the year
::                    -- DateStr [in,opt]  - date string, e.g. "3/31/2006" or "Fri 03/31/2006" or "31.3.2006", or omit form current date
:$reference http://groups.google.com/group/alt.msdos.batch.nt/browse_frm/thread/a0c34d593e782e94/50ed3430b6446af8#50ed3430b6446af8
:$created 20080612 :$changed 20080612 :$categories DateAndTime
:$source http://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
set /a "yy=10000%yy% %%10000,mm=1,dd=1"
set /a JD-=-1+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

TOP
2008-02-19
:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
Description:
call:Unique ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
::          -- ret    [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
    for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
        set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b

TOP
2008-02-19
:CmpFTime - compares the time of two files, succeeds if condition is met, fails otherwise
Description:
call:CmpFTime op file1 file2 attr1 attr2
Script:
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.
:CmpFTime op file1 file2 attr1 attr2 -- compares the time of two files, succeeds if condition is met, fails otherwise
::                  -- op    [in]     - compare operator, see 'IF /?', i.e.EQU, NEQ, LSS, LEQ, GTR, GEQ
::                  -- fileL [in]     - file name, left side of comparisation
::                  -- file2 [in]     - file name, right side of comparisation
::                  -- attrL [in,opt] - time field to be used for fileL, see 'dir /?', i.e. /tc, /ta, /tw, default is /tw
::                  -- attrR [in,opt] - time field to be used for fileR, default is attrL
:$created 20060101 :$changed 20080219 :$categories DateAndTime,FileOperation
:$source http://www.dostips.com
SETLOCAL
set op=%~1
set fileL=%~2
set fileR=%~3
set attrL=%~4
set attrR=%~5
if "%op%"=="" set op===
if "%attrL%"=="" set attrL=/tw
if "%attrR%"=="" set attrR=%attrL%
for /f "tokens=1-6 delims=/: " %%a in ('"dir %attrL% /-c "%fileL%"|findstr "^^[0-1]""') do (
    set TL=%%c%%a%%b%%f%%d%%e
)
for /f "tokens=1-6 delims=/: " %%a in ('"dir %attrR% /-c "%fileR%"|findstr "^^[0-1]""') do (
    set TR=%%c%%a%%b%%f%%d%%e
)
if "%TL%" %op% "%TR%" (rem.) ELSE set=2>NUL
EXIT /b




     

No comments:

Post a Comment