Get parent directory name for a particular file using DOS Batch scripting

see this question

@echo OFF
set mydir="%~p1"
SET mydir=%mydir:\=;%

for /F "tokens=* delims=;" %%i IN (%mydir%) DO call :LAST_FOLDER %%i
goto :EOF

:LAST_FOLDER
if "%1"=="" (
    @echo %LAST%
    goto :EOF
)

set LAST=%1
SHIFT

goto :LAST_FOLDER

you can use a vbscript, eg save the below as getpath.vbs

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile = objArgs(0)
WScript.Echo objFS.GetParentFolderName(strFile)

then on command line or in your batch, do this

C:\test>cscript //nologo getpath.vbs c:\test\pack\a.txt
c:\test\pack

If you want a batch method, you can look at for /?.

  %~fI        - expands %I to a fully qualified path name
  %~dI        - expands %I to a drive letter only
  %~pI        - expands %I to a path only

First answer above does not work if parent directory name contains a space. The following works:

@echo off
setlocal

set ParentDir=%~p1
set ParentDir=%ParentDir: =:%
set ParentDir=%ParentDir:\= %
call :getparentdir %ParentDir%
set ParentDir=%ParentDir::= %

echo ParentDir is %ParentDir%
goto :EOF

:getparentdir
if "%~1" EQU "" goto :EOF
Set ParentDir=%~1
shift
goto :getparentdir

Calling the above with parameter of "C:\Temp\Parent Dir With Space\myfile.txt" gives following:

>GetParentDir "C:\Temp\Parent Dir With Space\myfile.txt"
ParentDir is Parent Dir With Space

The above works by replacing spaces with colons (these should not exist in Windows paths), then replacing directory delimiters with spaces to so individual directories are passed to getparentdir as separate arguments. Function getparentdir loops until it finds its last argument. Finally any colons in result are replaced by spaces.


It can be very simple to get the parent folder of the batch file:

@echo off
for %%a in ("%~dp0\.") do set "parent=%%~nxa"
echo %parent%

And for a parent of a file path as per the question:

@echo off
for %%a in ("c:\test\pack\a.txt") do for %%b in ("%%~dpa\.") do set "parent=%%~nxb"
echo %parent%