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.

Comments (9)
  1. pc says:

    Well, the linked article specifically shows how “you can also do it without a subroutine” using the for command.

    Then again, I’d completely forgotten that this wasn’t the first time you’ve had Batch File Week, so the reminder was helpful.

    (At this point, Raymond’s done enough content that he could show reruns for quite some time, and a lot of people would still get a lot out of them. I’m pretty sure I’ve seen him talk about the redirection operators not at the end of the line before, but it may have just been on StackOverflow.)

  2. alegr1 says:

    I didn’t know you can also use the tilde operators on the loop variable.

  3. morlamweb says:

    I’ve used tilde operators in batch scripts for years. They’re well documented in the for-loop help: for/?

  4. jw says:

    It always seemed to me that shell scripting in Windows was more often than not abuse of FOR and IF commands to do something else useful they were probably not originally designed to do.

    1. AlexShalimov says:

      I think this can be said about almost any command (think about using PING or WAIT for getting delay).

      1. morlamweb says:

        ping -n X>NUL… yep, that’s in a lot of my scripts.

  5. florian says:

    My favorite FOR construct is this one from your blog:

    I often use it the other way round to check if %PATH% already includes the location of certain required executable files a script depends on.

    1. morlamweb says:

      Nowadays I use where.exe to check for something in the PATH. It’s much easier to remember than that one-liner.

  6. Neil says:

    My favourite FOR construct is this:

    for %%i in (“string with special characters”) do echo %%~i

    Works with anything you can quote. (So, not quotes themselves, unless you want a pair.)

Comments are closed.

Skip to main content