DosTips.com ... for VISTA,XP,NT,Server 2000,Server 2003,Server 2008
Search:
Last update:
Jan 21, 2008

DOS Batch - Functions

Keep your batch script clean, call DOS functions.


:append
appends a string to a specific line in a text file

:bannerPingPong
moves text in varref one step left or right and updates title

:bannerRotate
rotates text in varref one step and updates title

:choiceListInput
lets the user choose from list of last entered values

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

:count
counts the number of occurrences of needle in haystack

:date2jdate
converts a gregorian calender date to julian day format

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

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

:doProgress
display the next progress tick

:dumpArr
dump the array content / under construction

:echo
echoes text in a specific color

:echoLine
outputs a formatted string, substitutes file name and line number

:extractFileSection
extract a section of file that is defined by a start and end mark

:ExtractFunction
extract a function by label

:false
returns failure

:Format
output columns of strings right or left aligned

:fprop
return a file property

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

:getColorCode
convert color text to color code

:getDrives
returns array of drive information

:getFunctions
returns a comma separated list of all functions

:getHostName
resolved IP address to computer name

:getIP
return THIS computers IP address

:getRandomColor
returns a random color

:GetRegValue
Returns a registry value

:getServices
returns array of service information

:getVarsByAttr
returns a comma separated list of variables based on an attribute name

:htmlhelp
dumps html help to console

:Init
initializes the environment for this command library

:initProgress
initialize an internal progress counter and display the progress in percent

:initVarsByAttr
Restore the values of the persistent variables to defaults

:IsFileOpen
succeeds if file in use, fails otherwise

:IsRegKey
Succeeds if key exists

:IsRegValue
Succeeds if Key and Value exists

:IsServiceRunning
returns success if service is running, otherwise failure

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

:jdate2date
converts julian days to gregorian date format

:kBytesFree
returns the free space of a drive in kilobytes

:l2a
Convert a list to an array

:loadPersistentVars
Load the values of the persistent variables

:loadRegVars
Load the values of the persistent variables

:lookup
lookup key in map of key-value pairs

:lTrim
Strip whitespace (or other character) from the beginning of a string

:MakeAbsolute
makes a file name absolute considering a base path

:MakeRelative
makes a file name relative to a base path

:NetworkDeviceGuid2Name
get a Network Device Name from its coresponding GUID

:NetworkDeviceName2Guid
get a Network Device GUID from its coresponding Name

:parse
parse a string matching a formatter

:pwd
shows a password dialog box

:regedit
[IN] key - registry key to be shown after opening regedit

:removeArr
remove an array

:rTrim
Strip whitespace (or other character) from the end of a string

:savePersistentVars
Save values of persistent variables into a file

:saveRegVars
Save values of persistent variables into a file

:set
sets var[] to output of command / under construction

:SetRegValue
Returns a registry value

:sleep
waits some seconds before returning

:StartsWith
[IN] text - text to be searched

:strLen
returns the length of a string via binary search, maximum length 1023

:substitute
substitute a string in a text file

:ToANSI
converts a file to ANSI

:toCamelCase
convert a string to camel case

:toLower
convert uppercase character to lowercase

:ToUNICODE
converts a file to UNICODE

:toUpper
convert lowercase character to uppercase

:Trim
Strip whitespace (or other character) from the beginning and end of a string

:trimSpaces
trim spaces around string variable

:trimSpaces2
trim spaces around string and assigns result to variable

:true
returns success

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

DOS Batch - CMD Function Library
Need a new feature? It might already be scripted.

DOS Batch - Function Tutorial
What it is, why it`s important and how to write your own.

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


TOP
2008-02-19

:append - appends a string to a specific line in a text file

Description:
call:append str file line
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
:append str file line -- appends a string to a specific line in a text file
::                    -- str  [in] - string to be appended
::                    -- file [in] - file name to append the string to
::                    -- line [in] - line number to append the string to, first line is 1, omit for last line
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
set ap=%~1
set f=%~2
set c=%~3
if not defined c (
    set c=0
    for /f %%a in ('find /v /c ""^<"%f%"') do set c=%%a
)
(for /f "tokens=1,* delims=:" %%a in ('findstr /v /n "$$"^<"%f%"') do (
    if "%%a"=="%c%" (echo.%%b%ap%) ELSE echo.%%b
))>"%temp%.\t0815.txt"
move /y "%temp%.\t0815.txt" "%f%"
EXIT /b

TOP
2008-02-19

:bannerPingPong - moves text in varref one step left or right and updates title

Description:
call:bannerPingPong varref
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
:bannerPingPong varref -- moves text in varref one step left or right and updates title
::                     -- varref [in,out] - variable name with banner text, format: "Banner Text------"
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set s=!%~1: =-!
if "!s:~-1!" NEQ "-" if "!s:~-1!" NEQ "+" set s=!s!--------
set d=!s:~-1!
if "!s:~0,1!" NEQ "-" set d=+
if "!s:~-2,1!" NEQ "-" set d=-
if "!d!"=="+" (set s=-!s:~0,-2!+) ELSE (set s=!s:~1,-1!--)
TITLE !s!
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%s%
)
EXIT /b

TOP
2008-02-19

:bannerRotate - rotates text in varref one step and updates title

Description:
call:bannerRotate varref
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:bannerRotate varref -- rotates text in varref one step and updates title
::                   -- varref [in,out] - variable name with banner text, format: "Banner Text------"
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set s=!%~1: =-!
set s=!s:~1!!s:~0,1!
TITLE !s!
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%s%
)
EXIT /b

TOP
2008-02-19

:choiceListInput - lets the user choose from list of last entered values

Description:
call:choiceListInput ret list title max
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.
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.
:choiceListInput ret list title max -- lets the user choose from list of last entered values
::                                  -- ret   [out]    - varref returns input value
::                                  -- list  [in,out] - varref with choice list, returns trimmed reordered choice list
::                                  -- title [in]     - list title
::                                  -- max   [in]     - maximum number of list entries
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set l=,!%~2!,&          rem.-- get the choice list
set t=%~3&              rem.-- get the list title
set c=%~4&              rem.-- get the list entry count limit
set m=&                 rem.-- a message
set l2=,
set v=
:choiceListInput_LOOP1
echo.%t%
set i=0&for /f "delims=" %%a in ('"echo.%l:,=&echo.%"') do (
    set /a i+=1
    set l2=!l2!!i!;%%~a,
    set v=%%~a
    echo.  !i! - %%~a
)
if "%m%" NEQ "" echo.  ^>^> %m%
echo.  Make a choice or enter a new value [%v%]
set v1=%v%
set /p v1=  :
echo.
set v2=!v1!&set v2=!v2:,=!&set v2=!v2:@=!&set v2=!v2:;=!&set v2=!v2:"=!
rem.--reject entry with illegal character
if "!v1!" NEQ "!v2!" (
    set m=Note: ,;@" and empty string not allowed.  Try again.
    goto:choiceListInput_LOOP1
)
rem.--if first character is minus then remove the entry
set remove=&if "%v1:~0,1%"=="-" set remove=y&set v1=%v1:~1%
set v=%v1%
rem.--if number chosen then find corresponding value
set l3=!l2:,%v%;=,@!
if "%l3%" NEQ "%l2%" (
    for /f "delims=@ tokens=2" %%a in ("!l3!") do set l3=%%a
    for /f "delims=,"          %%a in ("!l3!") do set v=%%a
)
rem.--remove value from list if exist
set l3=%l%
set l=!l:,%v%,=,!
if "%remove%"=="y" (
    if "%l%"=="%l3%" (set m='%v%' cannot be removed from list
    ) ELSE (set m='%v%' has been removed from list)
    goto:choiceListInput_LOOP1
)
if "%l%"=="%l3%" echo.  ^>^>'%v%' has been added to the list
rem.--add to the value to the end
set l=!l:~1!%v%
rem.--enforce the list entry count limit if requested
if "%c%" NEQ "" (
    set i=0&for %%a in (%l%) do set /a i+=1
    if /i !i! GTR !c! (
        for /f "delims=, tokens=1,*" %%a in ("!l!") do (
            set l=%%b
            echo.  ^>^>'%%a' dropped out of the list
        )
    )
)
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" (SET %~1=%v%) ELSE (echo.%v%)
    IF "%~2" NEQ "" (SET %~2=%l%) ELSE (echo.%l%)
)
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
:$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

TOP
2008-02-19

:count - counts the number of occurrences of needle in haystack

Description:
call:count needle haystack ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
:count needle haystack ret -- counts the number of occurrences of needle in haystack
::                         -- needle   [in]  - string to find
::                         -- haystack [in]  - string to search in
::                         -- ret      [out] - valref for return value
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
set haystack=%~2
set /a ret=0
FOR /f %%a in ('"(echo.%%map:%~1=&echo.%%)|find /c /v """') DO set /a ret=%%a-1
( ENDLOCAL & REM RETURN VALUES
    IF "%~3" NEQ "" (SET %~3=%ret%) ELSE ECHO.%ret%
)
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.
: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
:$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"
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-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
:$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

: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
:$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
2008-03-27

:doProgress - display the next progress tick

Description:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
:doProgress -- display the next progress tick
:$created 20060101 :$changed 20080327
:$source http://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

TOP
2008-02-19

:dumpArr - dump the array content / under construction

Description:
call:dumpArr arr
Script:
1.
2.
3.
4.
5.
6.
7.
8.
:dumpArr arr -- dump the array content / under construction
::           -- arr [in]  - array name
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
call set i=%%%~1[#]%%
for /l %%n in (1,1,%i%) do call echo."%%%~1[%%n]%~2%%"
EXIT /b

TOP
2008-02-19

:echo - echoes text in a specific color

Description:
call:echo col txt
Dependencies:
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.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
:echo col txt -- echoes text in a specific color
::            -- col [in]  - color code, append a DOT to omit line break, call 'color /?' for color codes
::            -- txt [in]  - text output
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
for /f "tokens=1,*" %%a in ("%*") do (
    set col=%%a
    set txt=%%~b
)
set cr=Y
if "%col:~-1%"=="." (
    set cr=N
    set col=%col:~0,-1%
)
call:getColorCode "%col%" col
set com=%temp%.\color%col%.com
if not exist "%com%" (
    echo.N %COM%
    echo.A 100
    echo.MOV BL,%col%
    echo.MOV BH,0
    echo.MOV SI,0082
    echo.MOV AL,[SI]
    echo.MOV CX,1
    echo.MOV AH,09
    echo.INT 10
    echo.MOV AH,3
    echo.INT 10
    echo.INC DL
    echo.MOV AH,2
    echo.INT 10
    echo.INC SI
    echo.MOV AL,[SI]
    echo.CMP AL,0D
    echo.JNZ 109
    echo.RET
    echo.
    echo.r cx
    echo.22
    echo.w
    echo.q
)|debug>NUL
"%com%" %txt%
rem del "%com%" /q
if "%cr%"=="Y" echo.
EXIT /b

TOP
2008-05-12

:echoLine - outputs a formatted string, substitutes file name and line number

Description:
call:echoLine uniqueStr formatter offset
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
:echoLine uniqueStr formatter offset -- outputs a formatted string, substitutes file name and line number
::                                   -- uniqueStr [in]     - a unique string to identify the line
::                                   -- formatter [in,opt] - a string using __FILE__ and/or __LINE__ to be substituted and echoed
::                                   -- offset    [in,opt] - offset to be added to the line number
:$reference http://www.dostips.com/forum/viewtopic.php?t=369
:$created 20080512 :$changed 20080512
:$source http://www.dostips.com
Setlocal Disabledelayedexpansion
Set "Fmt=%~2"
If Not Defined Fmt Set "Fmt=__FILE__(__LINE__): ERROR"
For /F "Delims=:" %%A In ('"Findstr /N "%~1" "%~f0""') Do Set /A "lineNr=%%A+%~30/10"
Call Set "Fmt=%%Fmt:__LINE__=%lineNr%%%"
Call Echo.%%Fmt:__FILE__=%~nx0%%
EXIT /b

TOP
2008-12-04

:extractFileSection - extract a section of file that is defined by a start and end mark

Description:
call:extractFileSection StartMark EndMark FileName
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
: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 20081204 :$categories ReadFile
:$source http://www.dostips.com
SETLOCAL
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

TOP
2008-02-19

:ExtractFunction - extract a function by label

Description:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:ExtractFunction func -- extract a function by label
::                    -- func [in] - name of the function to be extracted
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set func=%~f0
set /a b=2000000000
set /a e=2000000000
for /f "tokens=1,* delims=:" %%a in ('"findstr /n /b /c:"%~1 " "%func%""') do set /a b=%%a
for /f "tokens=1,* delims=:" %%a in ('"findstr /n /b /c:"EXIT /b" "%func%""') do (
    if /i %b% LSS %%a if /i %%a LSS !e! set /a e=%%a
)
SETLOCAL DISABLEDELAYEDEXPANSION&  rem --disabling preserves excamation marks in %%b
for /f "tokens=1,* delims=[]" %%a in ('"find /n /v "" "%func%""') do (
    if /i %b% LEQ %%a if /i %%a LEQ %e% echo.%%b
)
EXIT /b

TOP
2008-02-19

:false - returns failure

Description:
call:false
Script:
1.
2.
3.
4.
5.
:false -- returns failure
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
set=2>NUL
EXIT /b

TOP
2008-02-19

:Format - output columns of strings right or left aligned

Description:
call:Format fmt str1 str2 ...
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
:Format fmt str1 str2 ... -- output columns of strings right or left aligned
::                        -- fmt [in] - format string specifying column width and alignment, i.e. "[-10][10][10]"
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
set "fmt=%~1"
set "line="
set "spac=                                                     "
set "i=2"
for /f "tokens=1,2 delims=[" %%a in ('"echo..%fmt:]=&echo..%"') do (
    call call set "s=%%%%~%%i%%%spac%%%%%~%%i%%"
    call set "fill=%%a"
    set /a i+=1
    if %%b0 GEQ 0 (call set "s=%%s:~0,%%b%%"
    ) ELSE        (call set "s=%%s:~%%b%%")
    call set "line=%%line%%%%fill:~1%%%%s%%"
)
echo.%line%
EXIT /b

TOP
2008-02-19

:fprop - return a file property

Description:
call:fprop filename prop ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
:fprop filename prop ret -- return a file property
::                       -- filename  [in]  - file name
::                       -- prop      [in]  - property, i.e.: d p n x a f s t z
::                       -- ret       [out] - return value
:$created 20060101 :$changed 20080219 :$categories FileInfo
:$source http://www.dostips.com
SETLOCAL
set ret=
for %%a in ("%~1") do set ret=%%~%~2a
( ENDLOCAL & REM RETURN VALUES
    IF "%~3" NEQ "" (SET %~3=%ret%) ELSE echo.%ret%
)
EXIT /b

TOP
2008-02-19

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

Description:
call:ftime JD filename attr
Dependencies:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
:ftime JD filename attr -- compares the time of two files, succeeds if condition is met, fails otherwise
::                  -- 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 20080219
:$source http://www.dostips.com
SETLOCAL
set file=%~2
set attr=%~3
if "%attr%"=="" set attr=/tw
for /f %%a in ('"dir %attr% /-c "%file%"|findstr "^^[0-1]""') do set T=%%a
call:jdate JD "%T%"
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" (SET %~1=%JD%) ELSE (echo.%JD%)
)
EXIT /b

TOP
2008-02-19

:getColorCode - convert color text to color code

Description:
call:getColorCode col ret
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.
:getColorCode col ret -- convert color text to color code
::                    -- col [in]  - color text BackgroundForeground, i.e.: BlueLYellow for 1E
::                    -- ret [out] - return variable to return color code in
:$created 20060101 :$changed 20080219 :$categories Color,Echo
:$source http://www.dostips.com
SETLOCAL
set col=%~1
set col=%col:Gray=8%
set col=%col:LBlue=9%
set col=%col:LGreen=A%
set col=%col:LAqua=B%
set col=%col:LRed=C%
set col=%col:LPurple=D%
set col=%col:LYellow=E%
set col=%col:LWhite=F%
set col=%col:Black=0%
set col=%col:Blue=1%
set col=%col:Green=2%
set col=%col:Aqua=3%
set col=%col:Red=4%
set col=%col:Purple=5%
set col=%col:Yellow=6%
set col=%col:White=7%
ENDLOCAL & IF "%~2" NEQ "" (SET %~2=%col%) ELSE (echo.%col%)
EXIT /b

TOP
2008-02-19

:getDrives - returns array of drive information

Description:
call:getDrives var
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:getDrives var -- returns array of drive information
::             -- var [out] - return variable, as array
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
set %~1=
set /a %~1[#]=0
for /f "tokens=*" %%a in ('fsutil fsinfo drives^|find /v ""') do (
    set /a %~1[#]+=1
    set i=%%a
    call set %~1[%%%~1[#]%%]=%%i:~-3%%
)
call set i=%%%~1[#]%%
for /L %%n in (1,1,%i%) do (
    for /f "tokens=1,* delims=- " %%a in ('"fsutil fsinfo drivetype %%%~1[%%n]%%"') do set %~1[%%n][drivetype]=%%b
    for /f "tokens=1,* delims=:" %%a in ('"fsutil volume diskfree %%%~1[%%n]%%|findstr /i avail"') do set %~1[%%n][avail]=%%b
)
EXIT /b

TOP
2008-02-19

:getFunctions - returns a comma separated list of all functions

Description:
call:getFunctions ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:getFunctions ret -- returns a comma separated list of all functions
::                -- ret [out] - reference to return variable
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
set ret=
for /f %%a in ('"findstr "^^:[a-z].*--" "%~f0" "') do call set ret=%%ret%%%%a,
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" (SET %~1=%ret%) ELSE ECHO.%ret%
)
EXIT /b

TOP
2008-02-19

:getHostName - resolved IP address to computer name

Description:
call:getHostName ip ret
Dependencies:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:getHostName ip ret -- resolved IP address to computer name
::         -- ip  [in,opt]  - ip, default is THIS computer's IP
::         -- ret [out,opt] - computer name
:$created 20060101 :$changed 20080219 :$categories Network
:$source http://www.dostips.com
SETLOCAL
set ip=%~1
if "%ip%"=="" call:getIP "" ip
set name=
for /f "tokens=2" %%a in ('"ping /a /n 1 %ip%|find "Pinging" 2>NUL"') do set name=%%a
ENDLOCAL & IF "%~2" NEQ "" (SET %~2=%name%) ELSE (echo.%name%)
EXIT /b

TOP
2008-02-19

:getIP - return THIS computers IP address

Description:
call:getIP host ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:getIP host ret -- return THIS computers IP address
::              -- host [in,opt]  - host name, default is THIS computer
::              -- ret  [out,opt] - IP
:$created 20060101 :$changed 20080219 :$categories Network
:$source http://www.dostips.com
SETLOCAL
set host=%~1
set ip=
if "%host%"=="" ( for /f "tokens=2,* delims=:. " %%a in ('"ipconfig|find "IP Address""') do set ip=%%b
) ELSE ( for /f "tokens=2 delims=[]" %%a in ('"ping /a /n 1 %host%|find "Pinging" 2>NUL"') do set ip=%%a)
ENDLOCAL & IF "%~2" NEQ "" (SET %~2=%ip%) ELSE (echo.%ip%)
EXIT /b

TOP
2008-02-19

:getRandomColor - returns a random color

Description:
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:getRandomColor ret -- returns a random color
::                  -- ret [out,opt] - return variable to return color code in
:$created 20060101 :$changed 20080219 :$categories Color
:$source http://www.dostips.com
SETLOCAL
set HEX=0123456789ABCDEF
set /a r1=%random% %% 16
set /a r2=%random% %% 16
call set rndcolor=%%HEX:~%r1%,1%%%%HEX:~%r2%,1%%
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%rndcolor%) ELSE (echo.%rndcolor%)
EXIT /b

TOP
2008-02-19

:GetRegValue - Returns a registry value

Description:
call:GetRegValue Key Value Data Type
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
:GetRegValue Key Value Data Type -- Returns a registry value
::                               -- Key    [in]  - registry key
::                               -- Value  [in]  - registry value
::                               -- Data   [out] - return variable for Data
::                               -- Type   [out] - return variable for Type, i.e.: REG_SZ, REG_MULTI_SZ, REG_DWORD_BIG_ENDIAN, REG_DWORD, REG_BINARY, REG_DWORD_LITTLE_ENDIAN, REG_NONE, REG_EXPAND_SZ
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set Key=%~1
set Val=%~2
if "%Val%"=="" (set v=/ve) ELSE set v=/v "%Val%"
set Data=
set Type=
for /f "tokens=2,* delims= " %%a in ('reg query "%Key%" %v%^|findstr /b "....%match%"') do (
    set Type=%%a
    set Data=%%b
)
( ENDLOCAL & REM RETURN VALUES
    IF "%~3" NEQ "" (SET %~3=%Data%) ELSE echo.%Data%
    IF "%~4" NEQ "" (SET %~4=%Type%)
)
EXIT /b

TOP
2008-02-19

:getServices - returns array of service information

Description:
call:getServices var
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:getServices var -- returns array of service information
::               -- var [out] - return variable, as array
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
set /a %~1[#]=0
for /f "tokens=*" %%x in ('"sc queryex state= all type= service"') do (
    for /f "tokens=1,* delims=: " %%a in ("%%x") do (
        if "%%a"=="SERVICE_NAME" set /a %~1[#]+=1
        call set %~1[%%%~1[#]%%][%%a]=%%b
    )
)
EXIT /b

TOP
2008-02-19

:getVarsByAttr - returns a comma separated list of variables based on an attribute name

Description:
call:getVarsByAttr attr ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
:getVarsByAttr attr ret -- returns a comma separated list of variables based on an attribute name
::             -- attr [in]  - attribute name
::             -- ret  [out] - reference to return variable
:$created 20060101 :$changed 20080219
:$source http://www.dostips.com
SETLOCAL
set varattr=%~1
set value=
FOR /F "usebackq tokens=1,2 delims=.=" %%a IN (`set`) DO if "%%a"=="%varattr%" (set value=!value!%%b,)
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" SET %~2=%value%
)