首页 > 技术文章 > bat 获取当前目录的父目录

ibingshan 2019-05-22 17:22 原文

bat 获取当前目录的父目录

@echo off
echo batchfile=%0
echo full=%~f0
setlocal
  for %%d in (%~dp0.) do set Directory=%%~fd
  echo Directory=%Directory%
  for %%d in (%~dp0..) do set ParentDirectory=%%~fd
  echo ParentDirectory=%ParentDirectory%
endlocal

pause

 注意:如果目录带有空格,则会获得当前路径,下面的支持空格路径:(参考链接:bat脚本中获取当前目录的上级目录 - it610.com

 

@echo off

set currPath=%~dp0
set parentPath=
:beginFindParent
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 endFindParent
set parentPath=%parentPath%%front%\
goto beginFindParent
:endFindParent
rem 获得的parentPath路径以\结尾
rem echo %parentPath% 

 注意:以上方法,如果currPath是一个文件,则会失败

推荐阅读