August 3rd, 2017

Decomposing file paths (and extracting other information like file size, date and time, and attributes) from a batch file

We saw something very similar to this during the first Batch File Week. You have a file name in an environment variable, and you want to decompose its path (say, extract the drive letter or get the file base name without any path information or extension). Or you want to get the file’s size or date or attributes.

The technique we saw in the article was to call a subroutine with the file name, and have the subroutine use the tilde operators to extract information from the inbound parameter.

You can also do this inline (without needing a subroutine) by abusing the FOR command. Tilde operators work on FOR loop variables, so you just need to set up a FOR loop that doesn’t actually loop!

set FILENAME=C:\Program Files\desktop.ini
for %%i in ("%FILENAME%") do set SIZE=%%~zi

Ta-da, you put the file size in the SIZE variable.

Of course, you could do actual math, too. Or use the other tilde operators to extract other information. Go nuts.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.