Determine parent folder name without entire folder path?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
djangofan
Posts: 23
Joined: 04 Nov 2011 12:28

Re: Determine parent folder name without entire folder path?

#16 Post by djangofan » 08 Nov 2011 17:22

So, after some fiddling, I have improved it a little more. Still might have bugs. Windows will not allow you to create a directory with a trailing "." and so that use-case probably isn't an issue:

Code: Select all

@echo off
SET "CDIR=%~p0"
:: for loop requires removing trailing backslash from %~p0 output
SET "_CDIR=%CDIR:~0,-1%"
FOR %%i IN ("%_CDIR%") DO SET "_PARENTFOLDERNAME=%%~nxi"
ECHO Parent folder: %_PARENTFOLDERNAME%
ECHO Full path: %~dp0
pause>nul

djangofan
Posts: 23
Joined: 04 Nov 2011 12:28

Re: Determine parent folder name without entire folder path?

#17 Post by djangofan » 03 Jan 2012 15:33

Finally! After all the help you guys gave me, here is the holy grail:

suggestion earlier in this thread that didn't quite work :

Code: Select all

for %%i in ("%~dp0.") do echo ParentFolderName = "%%~nxi"


related to that answer, this works:

Code: Select all

for /f "delims=\" %%a in ("%cd%") do echo topmost dir: %%~nxa

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

Re: Determine parent folder name without entire folder path?

#18 Post by orange_batch » 03 Jan 2012 18:55

I've written a complex function for the same purpose, so maybe I can help... This is a very simplified version (it is unable to handle paths at the drive root and first level).

The behaviour of a trailing backslash is actually a useful thing to exploit. You can determine if a path is a folder, a file, or nonexistent. In this case we're just stripping trailing backslashes though, to format folder paths.

Get parent folder name:

Code: Select all

set "check=C:\My\Folder\Path\"

if "%check:~-1%"=="\" set "check=%check:~,-1%"
for %%a in ("%check%") do set "check=%%~dpa"
for %%a in ("%check:~,-1%") do echo Parent folder: "%%~nxa"

django, you probably know, but your top most dir function returns the drive letter for fully qualified paths.

Post Reply