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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alo
Posts: 3
Joined: 14 Jul 2009 13:30

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

#1 Post by alo » 14 Jul 2009 13:39

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

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#2 Post by avery_larry » 14 Jul 2009 20:02

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%

alo
Posts: 3
Joined: 14 Jul 2009 13:30

#3 Post by alo » 15 Jul 2009 11:12

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

Post Reply