Get current folder name by a DOS command?

Solution 1:

Shortest way I have found:

for %I in (.) do echo %~nxI

or within a .bat script:

for %%I in (.) do echo %%~nxI

or in .bat with Get value in variable.

for %%I in (.) do set CurrDirName=%%~nxI
echo %CurrDirName%

Explanation: http://www.robvanderwoude.com/ntfor.php

nx means file name and extension only

Solution 2:

If you want to know the current location of the batch file (and if your Windows isn't a very ancient release), type for /? in a 'DOS box' window. Scroll down. Read.

You'll find out, that you can now read (from within the batch file) these variables:

%0      - as the name how this batchfile was called
%~d0    - as the drive letter where this batchfile is located ('\\' in case of share)
%~p0    - as path (without the drive letter) where this batchfile is located
%~n0    - as filename (without suffix) of this batchfile
%~x0    - as filename's suffix (without filename) of this batchfile
%~a0    - as this batchfile's file attributes
%~t0    - as this batchfile's date+time
%~z0    - as this batchfile's filesize
%~dpnx0 - as this batchfile's fully qualified path+filename
[... and then some more ...]

This works for many cases. Assume, the batchfile is called mytest.bat. You may call it in different ways:

  1. ..\..\to\mytest.bat ............................... (relative path)
  2. d:\path\to\mytest.bat ........................... (full path)
  3. \\fileserver\sharename\mytest.bat ... (path on remote share)

...and you'll always get the right value in your variables.