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

Raymond Chen

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.


Discussion is closed.

Feedback usabilla icon