logo To Foot
© J R Stockton, ≥ 2010-01-09

MS-DOS Batch Files.

No-Frame * Framed Index * Frame This
Links within this site :-

There is a ZIPped snapshot including these Batch pages (420kB+), taken on or after 2010-02-17; unZIP it in an empty directory.

Until 2006-10-14, I used Win98 1st Edn.
From 2006-10-19, I used Win XP sp2; from 2008-07-06, XP sp3.

Introduction to Batch Pages

NOTE : I have, operational, a MS-DOS 6.20 system and a DOS 3.3 system. I used to have a Win98 1st Edn system. I now have, and mainly use, a new WinXP system.

These pages are written largely from experience with Amstrad MS-DOS 3.3, MS-DOS 3.2 to 6.20, and MS-DOS boxes in MS Windows 3.x and MS Windows 98 1st release. There is much that I have not tried, and that therefore is not represented here.

My pages comprise snippets, and are not a tutorial.

General PC links, including MiniTrue, are in PC Links Reference.

For compatibility, I have generally created file names to DOS 8.3 format. My programs and batch files are designed with standard DOS 8.3 file names (SFN) in mind, though allowance may be made for Long File Names (LFN).

NOTE : I execute batch files from a command line prompt, not by clicking on something.

Windows NT, XP, etc. have much more powerful batch languages than DOS...Win98/ME, and are scarcely considered here. Windows 9x & ME can run the alternative command processor WIN95CMD, and others; the default command processor will be presumed to be in use.

I know very little of Windows ME, NT, 2000, and 2003.

Windows NT, XP, ...

NT and XP by default use CMD.EXE as the command processor, which is much more powerful than MS-DOS's COMMAND.COM - and sufficiently different to break many DOS batch files. But, it seems, NT, Win2K, and XP all come with a COMMAND.COM resembling that of MS-DOS, which can be run like any other program ...; and real-mode programs shell to it.

They may run DOS or 16-bit programs in a sub-shell loaded for each.

In NT+ batch, some of characters ^ $ (%?) ! & are special; they can be escaped to themselves with ^.

for /f %t in ('CD') do @set XX=%t ; store output of CD command

See also in batprogs#NTXP.

Windows Vista

Vista can run PowerShell, earlier called Microsoft Command Shell (MSH), codenamed "Monad".

Batch FAQs

Programmers :- you must get an up-to-date copy of Prof. Timo Salmi's Batch FAQ, from Garbo or from a mirror site such as SimtelNet, and study it intently. Sample announcement :-

 243153 Dec 27 2003 ftp://garbo.uwasa.fi/pc/link/tsbat.zip
 tsbat.zip Useful MS-DOS batch files and tricks, T.Salmi

See also his growing CMD.EXE FAQ. Sample announcement :-

 179284 Oct 21 2006 ftp://garbo.uwasa.fi/pc/link/tscmd.zip
 tscmd41.zip Useful NT/2000/XP script tricks and tips, T.Salmi

See also his Batch Links (among other sections).

And, read Terry Newton's batchfaq; and Laurence Soucy's Batfile FAQ; and Leonardo Pignataro's BATCH FAQ; and Eric Phelps' Windows 95 / DOS 7 Batch Programming; and


   14861 Mar 6 2002 ftp://garbo.uwasa.fi/pc/batchutil/batfaq23.zip
   batfaq23.zip FidoNet Echo BATPOWER Frequently Asked Questions

Batch Newsgroups

Also, read the relevant Newsgroups (the lists may need correction) :-

Those newsgroup references assume that the groups are carried on the local or default server, or are already subscribed to. Otherwise, try forms such as :-
http://groups.google.com/groups?as_ugroup=alt.msdos.batch.nt&as_scoring=d
news://news.microsoft.com/microsoft.public.win2000.cmdprompt.admin

However, any competent general news service should already carry those groups, or be willing to add them on request from a user (generally to newsmaster@...).

Don't make a fool of yourself by asking questions for which the answers are well documented, in FAQs, newsgroups, and/or elsewhere; or by using inappropriate newsgroups.

In newsgroups, it will normally be assumed that the default command processor is in use.

Be sure when asking for help to state the operating system(s) in use, and the localisation(s), whenever there is any chance that these may be significant.

Links

For Batch FAQs, see above.

For Batch, and for other purposes, one wants a good free plain-text editor :-

I use various editors including PFE, notepad, and DOS Edit.

Caveats on Date/Times

Some batch programmers briefly alter the OS date/time, perhaps in DEBUG script, to implement date or time arithmetic. Except in pure MS-DOS, this is an exceedingly dangerous method, since other processes may access the date or time while it is wrong. Ordinary testing may not reveal the hazard. None of my code does this.

As the date and time are acquired from the OS by separate operations, there is a risk of midnight rollover in between, giving a 24 hour error. Suitable programming, as in my NOWMINUS or otherwise, can make the reading effectively atomic.

A user program should not, without careful thought, use MS-DOS Int 1A/00, since that interrupt clears the midnight rollover flag at $40:70 but does not increment the daycount.

Rollovers

The MS-DOS file date-stamp, considered as a signed number, rolls over at the start of 2044; program error is possible.

Tools derived from UNIX or C code may fail at the January 2038 time_t rollover, if not properly updated.

TZ

UNIX-derived utilities may be affected, fully or partly, by a TZ environment variable; test carefully.

They may also use by default "local time_t" or "California time_t" rather than "UNIX time_t", i.e. with the Epoch at 1970-01-01 00:00:00 but not UTC. They may also assume particular US DST rules (for 1987-2006, NA DST started a week later than current EU ST; the times of changes also differ; NA rules changed from 2007, and both change dates now differ from those of the EU). In such cases, the TZ environment variable may well work, fully or partially, for setting the Time Zone.

MvdV has written, in this context, "Probably all DJGPP based programs do also.".

Date/Time Stamps

Traditional MS-DOS file date-stamps are stored in local time, resolution 2 seconds, and are generally displayed as such.

Windows Created/Accessed/Modified stamps are stored as a 64-bit count of 100 ns units from Gregorian 1601-01-01 00:00:00 GMT. When they are displayed, they are usually converted to user's local civil time. The Summer Time correction is dubious.

Subroutines in DOS Batch ??

One can have non-recursive calling of subroutine FRED within a single MS-DOS batch file (no use of CALL or another CP) as follows, three lines are used for each CALL, one for subroutine entry and one for return :-

	@echo off
	echo ENTRY
.	set FRED=xxx
.	GOTO FRED
.	:xxx
	echo BETWEEN
.	set FRED=yyy
.	GOTO FRED
.	:yyy
	echo END
	GOTO FINISH

.	:FRED
	echo --- %FRED%
.	GOTO %FRED%

	:FINISH
	echo Exeunt Omnes

which on execution gives me :-

	ENTRY
	--- xxx
	BETWEEN
	--- yyy
	END
	Exeunt Omnes

Note that FRED can invoke any other subroutine(s), which can invoke... , provided that there is no recursion of FRED.

Recursion appears possible, with difficulty.

Subroutine-files are also possible, of course.

Miscellaneous DOS Batch Information

See also MS-DOS Batch Introduction.

If a MS-DOS batch file is edited, say in another window, while it is being executed, confusion can occur.

COMMAND /z causes ERRORLEVEL to be shown, at least in Win98.

COMMAND /y /c batch.bat single-steps batch.bat.

The batch language depends to some extent on the version of DOS/Windows in use; NT/XP has considerably more than DOS..Win9x/ME.

Many batch file techniques rely on assumptions about DOS's national or language settings - date field order and separator being prime examples, and also actual wording. International standards should be used wherever practicable.

If transferring between systems, beware of Code Page issues for characters above #126.

Commands may have defaults altered by environment variables; see, for example, DIR /?, COPY /?; public batch files should allow for this.

DEL *.* requires confirmation; DEL *?.* does not, in some systems. DEL *.?* should only delete files with extensions.

"ECHO." gives a blank line; "ECHO." or "ECHO Y" can sometimes be piped into another program to pre-answer confirmation prompts - for example, "ECHO Y|DEL *.*".

Win9x : LFNFOR on/off controls use of LFN in FOR. Try LFNFOR /?.

Showing Benny Pedersen's ExitPrompt technique :
  ECHO.EXIT|%COMSPEC%/kPROMPT Date+time $d $t to STDOUT$_|find " "

Deletion of all *.eml files does not need a batch file :-
  HUNT \*.eml s q "del" u
Be careful with *.nws files; some are useful.

XCOPY with /D:yyyy-mm-dd and other options can be useful for selective copying; the date format can vary with location and perhaps version.

Consider Kan Yabumoto's free improvement, at XXCOPY.

Rename/Copy

Many simple renaming or copying tasks can be done by generating a list of file names with the /B option of DIR and then stream-editing the list to produce a batch file for examination and execution. Suitable editors include SED, MiniTrue, and my COLS. Remember that long file names may contain spaces.

dir /b | mtr -o -x+ - (.*)(EI)(.*)\r = 'ren "\1\2\3" "\1IE\3"\r'
:: for changing the first EI to IE in filenames, by MiniTrue-32

dir /b ??*.* | COLS 'ren * q 1- q * q 2 1 3- q
:: for swapping the first two characters in filenames

File Comparison

The following

fc file1 file2 | find /i "No differences encountered"

will fail if only one of the files contains the string No differences encountered. That may seem improbable; but if the line is used in a batch file, then at least one file on the system contains the line.

A safe solution is to test not for the presence of that string, but for the absence of the "separator" in the differences report, which in my system is ****** - provided that the comparison is actually text mode and not binary mode.

fc /b file1 file2 | find "FC: no differences encountered"

also appears to be safe.

If there are differences, those methods will use a potentially large intermediate file. One added byte makes most following bytes differ.

I have written a program "filecmpr" which compares files efficiently, giving one-line text result and an ErrorLevel.

Screen Colours

To change the colours of a DOS screen or window, without ANSI.SYS, use one of my DOS programs ATTRTEXT and SCRNHUES, at the foor of the screen; comment is in the PAS files. Colours are not preserved across standard CLS.

One can use MS-DOS DOSKEY to redefine CLS - DOSKEY CLS=type newlines.txt with newlines.txt containing fifty empty lines. Colours should then be preserved.

Undocumented DOS

Undocumented features should be avoided where possible, since they may not always work; but they can be rather useful. Doubtless there are full lists (where?) on the Web. Here are a few helpful for Batch users :-

Other Scripting in DOS and Windows

What tools are there other than those in "core" MS-DOS Batch, i.e. other than those that one would expect to find documented in the "Batch" chapters(s) of a good printed MS-DOS manual; and how does one find whether one indeed has them, and where does one look to install them, and what Help is available? See below for some.

Documentation

Where a batch requires tools that are not part of the default installation for the intended operating systems, ISTM that its descriptive part should include a line such as

:: Requires: GAWK

That seems a sufficient clue that there's no point in trying the file unless the tools are present. Sometimes, it will be worth giving a clue as to where the tool comes from (a Google for GAWK should be useful; one for my OVER, unless qualified, will find much cricket).

DOS Components

DEBUG

DEBUG is a primitive monitor which is still a standard part of MS-DOS. Being driven from standard input, it can be scripted by input redirection. For example, the memory-move script

M40:1A L2 40:1C
Q

should empty the keyboard buffer by making its begin and end pointers hold the same value.

DEBUG can be used, with its A command, to construct small programs from more-or-less readable text, which can be useful in batch. Its E command can compose programs directly in hexadecimal machine code, a practice which is unreadable and over-typo-prone.

As usual, DEBUG /? gives help on calling DEBUG; the command ? lists the other commands.

EDLIN

EDLIN is a primitive editor which used to be a standard part of MS-DOS, and can still be loaded in Windows (e.g. "Supplemental"). As it is driven from standard input, it can be scripted by input redirection.

To generate a test file containing lines Line00..Line09 :-

echo. | COLS !9 | COLS 'Line ^2,100 > TEST

Then with a script file SCR containing :-

SLine03
1,-1D
SLine07
+1,#D
e

by executing EDLIN TEST < SCR one gets just Line03..Line07 in TEST.

Consider also

attrib c:\*.bak > $$.bat
EKKO '1R * 'A * ^Z 'del 13 'E 13 | edlin $$.bat

But how, using pure MS-DOS, can one pipe a file with embedded ^Z into EDLIN? Such can be generated with echo and copy /b a+b c .

QBASIC

QBASIC became a standard part of MS-DOS; but it is not a default load in Windows 98. It has large common runtime code, but uses small scripts. A crude language; I don't know or care much about it. I believe that it can be installed from a Windows CD by ..., that its presence can be observed by executing QBASIC /?, and that an example of batch-style usage is (this is probably incorrect, as I don't use it) :-

File HI_WORLD.BAS :-
  PRINT "Hello World"
  END
Execute :-
  QBASIC /RUN HI_WORLD

DOS Imports

There are DOS versions of the scriptable UNIX utilities GREP, AWK, SED, etc. Seek these at FTP Garbo in the PC section, in sub-directories such as editor, filefind, fileutil, unix. File 0unix.zip describes files in the UNIX directory.

AWK, GAWK

Batch FAQ TSBAT75 (via ZIP) included :-

  GAWK.EXE A Pattern Scanning and Processing Language
    233923 Mar 25 1995 ftp://garbo.uwasa.fi/pc/unix/gawk2156.zip
    GNU awk text scanning and processing language
    (Note, use this older version, not the more recent ones!)

With this, GAWK --version gives Gnu Awk (gawk) 2.15, patchlevel 6.

NOTE : This GAWK apparently has time functions preset for Time Zone -0800, California time (with their 1987-2006 DST dates). It partly understands a TZ environment variable for setting the Zone and for enabling Summer Time; but it does not honour the Summer Time change dates in TZ.

Because of these, arithmetic on systime() may, if spanning certain times of the year, lead to incorrect results outside North America. Remember that a one-hour error, in a job scheduled to run within an hour of midnight, can give the wrong day.

NOTE : "Solutions" involving the adjustment of a value given by systime() by 24×60×60 or a multiple thereof will be unsafe in many countries, since the length of a civil day is not always 24 hours, but may be 23 or 25 hours. This is not a GAWK error, but a GAWK-user's error.

NOTE : This GAWK also uses, for strftime() %W, a Week Number not compliant with ISO 8601; it has a Week 0 before the First Monday. Moreover, strftime() %V, which supposedly gives the ISO week number, gets Mon/Tue/Wed Dec 29/30/31 wrong if the next Thursday is in the next Calendar Year. See GWN.

My program NOWMINUS can be used instead, for much date/time work in batch - see in MS-DOS Batch Programs, programs/.

SED

TSBAT75 includes :-

  SED.EXE Stream Editor
    20368 Oct 1 1991 ftp://garbo.uwasa.fi/pc/unix/sed15x.zip
    HHSED executable, E.Raymond+D.Kirschbaum+H.Helman

GREP

A text search and report utility, with RegExps : a super-FIND.

GREP by Stan Brown of Oak Road Systems (shareware) :-

  380097 May 5 16:06 ftp://garbo.uwasa.fi/pc/fileutil/grepsb80.zip
  grepsb80.zip Find regular expressions in files, also Win, S.Brown

PST wrote :- fgrep (fast grep) searches for strings (no REs) ; grep uses Basic Regular Expressions (BREs) similar to those used in ed, vi and sed ; egrep uses Extended Regular Expressions (EREs) similar to those used in awk.

MiniTrue

MiniTrue (16-bit mt.exe; 32-bit mtr.exe ?XP?) : file view, search, edit. The view, search and editing functions are useful from a DOS prompt; the search and editing functions are particularly useful in batch files, examples in batprogs#MT. I have used it frequently in maintaining this Web site.

It includes, more or less, the functionality of (at least) LIST, GREP, and SED.

Pascal

One can "script" Pascal as shown by (TPC is the Turbo Pascal command-line compiler) :-

echo "pascal code line" > xx.pas
echo "pascal code line" >> xx.pas
if exist xx.exe del xx.exe
call TPC xx
call xx < infile > outfile

See my Pascal Introduction ff.

Perl

Reportedly good; but I don't have it.

Windows Components

To generate a delay measured in seconds, type ping -h to see whether you have PING in your OS, and if so consider

 ping -n 6 127.0.0.1 > nul

for a five-second delay.

Win32 - Windows Scripting Host

Consider using Windows Scripting Host (WSH) to enhance or replace Batch; it can run (at least) JavaScript and VBScript in Win32.

WSH is a component of the standard installation for Windows 98 and XP; it could be installed in Windows 95.

CSCRIPT runs at a 32-bit Command Prompt box. In Win98 and XP, cscript and cscript //? give me brief Help.

WSCRIPT runs in GUI mode, and (by default) may also be started by double-clicking on a file of suitable extension in File Manager or in Internet Explorer. At a Command Prompt, wscript opens a properties dialog, and wscript //? gives similar brief Help to cscript.

A script can read the inherited environment. To write to the parent environment, it appears necessary to create a batch file containing SET commands and to execute it in the parent after the script is finished.

Note that date formats are dependent on system settings. Use order Y M D whenever possible, and use numbers instead of strings.

The script engines are shared with MS IE, and so have the same bugs; see via JavaScript Index and Introduction & VBScript General and Maths.

WSH has a successor, Microsoft Command Shell (MSH) (Monad), now called PowerShell, using ".NET".

Documentation?

I've not yet discovered where pleasing documentation on WSH and VBScript might be.

In Win98,
* C:\WINDOWS\SAMPLES\WSH\ seemed to contain a set of samples;
* C:\WINDOWS\HELP\WSCRIPT.HLP existed on my system;
* C:\WINDOWS\HELP\WSH.HLP should, it is said, exist.
*  Windows Script Host ?
* Microsoft Web site : scrdoc56en.exe extensive "Microsoft Windows Script Technologies" help file

Suggestion received : wsconwshbasics.asp; I've not liked it.

JavaScript in WSH

JavaScript is a scripting language often used within Web pages; but it can be run independently, and in servers. See also my JavaScript Index and Introduction and JavaScript Date and Time Introduction.

A simple example of creating and using a *.js file from within a Batch file :-

@echo off
echo WScript.Echo(new Date().toUTCString()); >tmp.js
cscript //nologo tmp.js
del tmp.js

That shows, in Win98 1st Edn, that the GMT/UTC date/time can at least be displayed, by interpreted JavaScript from a batch file, in a Win98 MS-DOS box. The output of the cscript line can be redirected or piped, e.g. in DOS..Win98 to my STOW. The following batch file sets environment GTZO to the offset of local time from GMT, in minutes :-

:: @echo off
find /v "@" < %0 > tmp.js
@cscript //nologo tmp.js | STOW gTzO > nul
:: @del tmp.js
@goto:eof
WScript.echo(new Date().getTimezoneOffset()) //
:eof @
@echo.

Note : that must be executed by name.bat as just name is insufficient. Use of DOS find means that the WSH script, here just one line (marked '//'), is written as executed except that @ must be avoided.

Batch (when in Win32) thus has access to, for example, GMT, Time Offset, and general calculation facilities.

I intend to look into this more.

@echo off
:: In Win32, use WSH/JS to set environment YYYYMMDD, using files tmp.*
echo var D = new Date() > tmp.js
echo D = (D.getFullYear()*100+D.getMonth()+1)*100+D.getDate() >> tmp.js
echo WScript.Echo( '@set YYYYMMDD='+D ) >> tmp.js
cscript //nologo tmp.js > tmp.bat
del tmp.js
call tmp
del tmp.bat
Read Arguments

File $98.js :-

x = WScript.Arguments
WScript.echo("Result:", x.length, typeof x, x(1), "OK")

Prompt>cscript //nologo $98.js 66 77 88
Result: 3 object 77 OK

The Arguments are 0-based. Note x(1) not x[1] .

Read Environment

File $98.js :-

var ws = WScript.CreateObject("WScript.Shell");
var en = new Enumerator(ws.Environment)
for ( en.moveFirst() ; !en.atEnd() ; en.moveNext() )
  WScript.echo(en.item())
ws = null

Prompt>cscript //nologo $98.js
Result: as for Prompt>SET but with an extra first line
Examples
To Show a Calendar
C:\EPHEMERA>type cal0.js

x = WScript.Arguments
Yr = x(0) ; Mo = x(1)

YS = "JanFebMarAprMayJunJulAugSepOctNovDec"
MN = Mo<1 || Mo>12 ? Mo : YS.substr(3*Mo-3, 3) // Month Name
WScript.echo(" ", Yr, "         ", MN)
WScript.echo(" Mo Tu We Th Fr Sa Su")
WD = new Date(Yr, Mo-1, 1).getDay() ;
if (WD==0) WD = 7 // Week Day Number of 1st
LD = new Date(Yr, Mo, 0).getDate() // Last Day of month
Wk = "" ; for (D=1 ; D < WD ; D++) Wk += "   "

for (D=1 ; D<=LD ; D++) {
  Wk = Wk + " " + (D<10 ? "0"+D : D) ; WD++
  if ((WD==8) || (D==LD)) { WScript.echo(Wk) ; WD = WD-7 ; Wk = "" }
  }

WScript.echo("        ------       ")


C:\EPHEMERA>cscript //nologo cal0.js 2010 1
  2010           Jan
 Mo Tu We Th Fr Sa Su
             01 02 03
 04 05 06 07 08 09 10
 11 12 13 14 15 16 17
 18 19 20 21 22 23 24
 25 26 27 28 29 30 31
        ------
To get ISO 8601 Week Number

See in datefmts for ISO 8601; weekinfo for weeks, weekcalc & include3 for the function.

C:\EPHEMERA>type calw.js
function YMD2YWD(y, m, d) { // ISO 8601 WkNo. m=1..12 (include3.js)
  var ms1d = 864e5, ms7d = 7*ms1d
  var DC3 = Date.UTC(y, m-1, d+3)/ms1d // an Absolute Day Number
  var DoW = 1 + (DC3+7777777)%7
  var AWN = Math.floor(DC3/7) // an Absolute Week Number
  var Wyr = new Date(AWN*ms7d).getUTCFullYear()
  return [Wyr, AWN - Math.floor(Date.UTC(Wyr, 0, 0)/ms7d), DoW ] }

var A = WScript.Arguments
YWD = YMD2YWD(+A(0), +A(1), +A(2))
WScript.echo( "@echo off" )
WScript.echo( " SET YYYYWWD=" + ((YWD[0]*100+YWD[1])*10+YWD[2]) )
WScript.echo( " SET    YYYY=" + YWD[0] )
WScript.echo( " SET      WW=" + ( (w=YWD[1]) > 9 ? w : "0"+w ) )
WScript.echo( " SET       D=" + YWD[2] )

C:\EPHEMERA>cscript //nologo calw.js  2005 5 6
@echo off
 SET YYYYWWD=2005185
 SET    YYYY=2005
 SET      WW=18
 SET       D=5

VBScript in WSH

VBScript is a scripting language often used in the manner of DOS Batch; and, less often, used within Web pages. See also my VBScript Date and Time and VBScript General and Maths.

In a MS-DOS box, cscript //nologo msg.vbs executes the file msg.vbs ; example :-

Msgbox "string"
Msgbox Date
S = Date
T = Time
s = "2000"+right(S, 6)
MsgBox S
MsgBox T

Use DateSerial in preference to CDate.

Read Arguments

File $98.vbs :-

Set x = WScript.Arguments
WScript.echo "Result:", x.count, X(1)

Prompt>cscript //nologo $98.vbs 66 77 88
Result: 3 77

The Arguments array is 0-based.

Read Environment

File $98.vbs :-

set ws = WScript.CreateObject("WScript.Shell")
set en = ws.Environment
WScript.echo "Result: ", en("Prompt")

Prompt>cscript //nologo $98.vb
Result:  $p$g
Example
C:\EPHEMERA>type cal0.vbs

Set X = WScript.Arguments : '' WScript.echo "Parameters:", X(0), X(1)
Yr = X(0) : Mo = X(1)

YS = "JanFebMarAprMayJunJulAugSepOctNovDec"
MN = Mid(YS, 3*Mo-2, 3) : if MN="" then MN = Mo '' Month Name
WScript.echo " ", Yr, "         ", MN
WScript.echo " Mo Tu We Th Fr Sa Su"
WD = WeekDay(DateSerial(Yr, Mo, 1), 2) '' Week Day Number of 1st
LD = Day(DateSerial(Yr, Mo+1, 0))      '' Last Day of month
Wk = Left("                     ", (WD-1)*3) '' Previous month

for D = 1 to LD
  Wk = Wk & " " & Right(100+D, 2) : WD = WD + 1
  if (WD=8) or (D=LD) then WScript.echo Wk : WD = WD-7 : Wk = ""
  next

Wscript.echo "        ------       "


C:\EPHEMERA>cscript //nologo cal0.vbs 2010 1
  2010           Jan
 Mo Tu We Th Fr Sa Su
             01 02 03
 04 05 06 07 08 09 10
 11 12 13 14 15 16 17
 18 19 20 21 22 23 24
 25 26 27 28 29 30 31
        ------
RegExp Example
'' $RE.VBS DRAFT; WORKING UNPOLISHED
'' To execute : CSCRIPT //NOLOGO $RE.VBS 012gg3456789hh765

Dim X, sLine, objRegExp, oMatches, oMatch
MsgBox "VBScript version " & ScriptEngineMajorVersion & _
  "." & ScriptEngineMinorVersion
Set X = WScript.Arguments
sLine = X(0)
' Set objRegExp = CreateObject("VBScript.RegExp")
Set objRegExp = New RegExp
With objRegExp
  .IgnoreCase = True
  .Global = True
  .Pattern = "\d{6,}"                ' Seek 6+ digits
  Set oMatches = .Execute(sLine)     ' Matches go into a collection
  MsgBox oMatches.Count & " matches"
  For Each oMatch in oMatches
    MsgBox "Match" & vbCrLf & oMatch ' TFirst match is the target
    Next
End With
' RegExp methods : Test(S) Execute(S) Replace(S, s)

VBScript Regular Expressions

Behaviour in DatePart

It appears that DatePart("ww", ... is intended to give the ISO 8601 Week Number. All ISO 8601 weeks have exactly seven days.

C:\JRS>type WN.VBS
WScript.echo "   Date      DoW   WN by DatePart"
for DD = 27 to 35
  CD = DateSerial(2007, 12, DD)
  WN = DatePart("ww", CD, vbMonday, vbFirstFourDays)
  WScript.echo CD, " ", WeekDayName(Weekday(CD), true), " ", WN
  Next

C:\JRS>cscript //nologo WN.VBS
   Date      DoW   WN by DatePart
2007-12-27   Thu   52
2007-12-28   Fri   52
2007-12-29   Sat   52
2007-12-30   Sun   52
2007-12-31   Mon   53
2008-01-01   Tue   1
2008-01-02   Wed   1
2008-01-03   Thu   1
2008-01-04   Fri   1

I see 52 52 52 52 53 1 1 1 1 in WinXP sp2 & sp3 IE7 & IE8, and Win98 would have given the same; I now expect the same from current (Mar 2007) Vista.

I understand that the same DLL code is used to execute VBS in Internet Explorer as in WSH; see also the more extensive testing in VBScript Date and Time 2; which shows that discrepancy three times per 28 years and another once per 400 years (to see that in WSH, use the above code with 2100 instead of 2007).

PowerShell seems to have Calendar.GetWeekOfYear(), similar to DatePart("ww",,,) and also imperfect.

To put DateTime in File Name

To set environment FN to a file name 'myfileYYYYMMDDhhmmss.txt' :

Put the following into a .js file, say $33.js :

  with (new Date()) WScript.echo("set FN=myfile" +
    ( getFullYear()*1e10 + (getMonth()+1)*1e8 + getDate()*1e6 +
    getHours()*1e4 + getMinutes()*1e2 + getSeconds() ) + ".txt")

Execute with

  cscript //nologo $$33.js > $$33.bat

Execute $33.bat, tidy up, use environment variable FN.

Or similarly with $$33.vbs :

  N = Now
  WScript.echo "set FN=myfile" & _
    ( Year(N)*1e10 + Month(N)*1e8 + Day(N)*1e6 + _
    Hour(N)*1e4 + Minute(N)*1e2 + Second(N) ) & ".txt"

Web Browsers

JavaScript and VBScript can be used in Web pages.

As implemented in Web browsers, such languages have selectable security restrictions.

PowerShell

It appears that PowerShell is intended to take the place of VBScript and supplement Batch - Install UK. News:microsoft.public.windows.powershell exists.

Windows PowerShell.

Others?

See also MS-DOS Batch Programs and MS-DOS Batch Introduction.
Home Page
Mail: no HTML
© Dr J R Stockton, near London, UK.
All Rights Reserved.
These pages are tested mainly with Firefox 3.0 and W3's Tidy.
This site, http://www.merlyn.demon.co.uk/, is maintained by me.
Head.