Page 1 of 1

Getting the name of the folder that the .bat is running from

Posted: 14 Jul 2009 13:39
by alo
I've read through many of the samples on this site and I must say very nice work. I sort of like trying to do things in dos not because it is the easiest but because it is like solving a puzzle.

Anyway I've experimented with my current puzzle long enough and it's time to ask all you smart people out there (who probably already know the answer in your sleep)

if i reference the %0 arg i seem to have options to either get the file name of the batch, ext, path, drive letter, etc.


all i am looking for is the name of the folder the .bat is in (the last part of %~dp0)


thanks in advance (i'm sure i'll have harder puzzles in the future)

:D

Posted: 14 Jul 2009 20:02
by avery_larry
Maybe someone has a cool way to do this -- but if you iterate through the folders until you have the last one . . :

Code: Select all

@echo off

set "fldr=%~dp0"
:loop
for /f "tokens=1* delims=\" %%a in ("%fldr%") do (
   if not "%%~b"=="" set "fldr=%%~b" && goto :loop
   set "fldr=%%~a"
)
echo %fldr%

Posted: 15 Jul 2009 11:12
by alo
thanks avery_larry

i gave up on the one-liner approach and decided that looping was the only way

your solution is better than what i ended up with - i had learned how to make a "for /d" loop but since it required a wildcard there was a chance it would get more than just the %~dp0 directory