Getting a Substring Out of Batch

One of my friends, Andrew from Vancouver, sent me this extremely useful tip about how to grab a sub-string via BATCH.
<snip>
 here's a CMD shell tip that works in W2K, WXP, and W2K3.

There is a BASIC MIDSTR function equivalent in batch files... use this syntax as a modifer:

~:start,end

e.g.

set foo=\\servername
@echo unretouched [%foo%]
@echo modified [%foo:~2,99%]

will output:

unretouched [\\servername]
modified [servername]
 

In a corporate network, this is a handy thing to have, for example, if you want to ping the server indicated in the LOGONSERVER variable, which is a UNC instead of just a host name:

ping %logonserver:~2,99%

Or let's say that you want the day of the week. This:

@echo unretouched [%date%]
@echo modified [%date:~0,3%]

will output:

unretouched [Tue 05/06/2008]
modified [Tue]

Nifty.
 

See the help at the end of “FOR /?” for other expansions to variables in file paths, some or all of which are repeated below.

See the Windows Help (no, seriously) and search for “using batch parameters” for lots of interesting expansions, e.g.

%~1 Expands %1 and removes any surrounding quotation marks (“”).
%~f1 Expands %1 to a fully qualified path name.
%~d1 Expands %1 to a drive letter.
%~p1 Expands %1 to a path.
%~n1 Expands %1 to a file name.
%~x1 Expands %1 to a file extension.
%~s1 Expanded path contains short names only.
%~a1 Expands %1 to file attributes.
%~t1 Expands %1 to date and time of file.
%~z1 Expands %1 to size of file.
%~$PATH:1 Searches the directories listed in the PATH environment variable and expands %1 to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found, this modifier expands to the empty string.
Andrew.

</snip>
Thanks Andrew!