Reputation: 361
It's about a Windows 7 droplet, a batch file on the desktop. I drag folders on it, and need to find the parent folder.
Drag: C:\abc\def\ghi\jkl <- jkl is a folder! Looking for "ghi" not "C:\abc\def\ghi"
Drag: C:\abc\def\ghi\jkl\mno\pqr <- pqr is a folder! Looking for "mno"
This code gives the last folder. But I need the next to last.
Parent folder name only, not the whole path to that parent folder.
Thanks.
@echo off
setlocal enableDelayedExpansion
echo Command line:
echo !cmdcmdline!
echo.
echo Whole path: "%~1"
set MYDIR=%~1
set MYDIR1=%MYDIR:~0%
for %%f in (%MYDIR1%) do set myfolder=%%~nxf
echo Most right folder: %myfolder%
pause
exit
Upvotes: 1
Views: 1645
Reputation: 56180
Two steps: first is equal to yours. Second: remove the \
at the end and do the same thing again:
for %%i in ("%~1") do set "parent=%%~pi"
for %%i in ("%parent:~0,-1%") do echo %%~nxi
Upvotes: 0
Reputation: 130829
Your code does not reliably give you the name of the right most folder. It fails if the folder name contains spaces.
Here is code that properly gives the right most folder, as well as the parent of that folder.
@echo off
setlocal enableDelayedExpansion
echo Command line:
echo !cmdcmdline!
echo.
echo Whole path: "%~1"
:: Here is the correct code to get the right most node (folder in your case)
echo Most right folder: "%~nx1"
:: Here is the code to get the parent of the right most node
for %%F in ("%~1\..") do echo Parent folder: "%%~nxF"
pause
exit
Upvotes: 2