@echo off
set currPath=%~dp0
set split=''
echo %currPath%
:begin
FOR /F "tokens=1,* delims=\" %%i IN ("%currPath%") DO (set split=%%i)
FOR /F "tokens=1,* delims=\" %%i IN ("%currPath%") DO (set currPath=%%j)
if not "%parentPath%" == "" goto gotJpdaOpts
set parentPath=%split%\
goto begin
:gotJpdaOpts
if %parentPath%%split%\==%~dp0 goto end
set parentPath=%parentPath%%split%\
goto begin
:end
echo %parentPath%
pause
下面这个脚本支持目录中带空格
@echo off
set currPath=%~dp0
set parentPath=
:begin
FOR /F "tokens=1,* delims=\" %%i IN ("%currPath%") DO (set front=%%i)
FOR /F "tokens=1,* delims=\" %%i IN ("%currPath%") DO (set currPath=%%j)
if not "%parentPath%" == "" goto gotJpdaOpts
:gotJpdaOpts
if "%parentPath%%front%\"=="%~dp0" goto end
set parentPath=%parentPath%%front%\
goto begin
:end
echo %parentPath%