批处理中的目录名称

时间:2009-05-01 16:29:50

标签: batch-file

如何在批处理文件中的变量中存储目录名?

5 个答案:

答案 0 :(得分:2)

set dirname=c:/some/folder

echo %dirname%

REM retrieve the last letter of the folder 
REM and save it in another variable

set lastLetter=%dirname:~-1%

echo %lastLetter%

答案 1 :(得分:0)

返回存储批处理文件的目录 %〜DP0

%0是批处理文件的完整路径

set src= %~dp0
echo %src%

当我希望某些文件相对于我的批处理文件时,我已经使用过这个文件。

答案 2 :(得分:0)

没有更多的精确度,很难帮助你......

也许你想要当前的目录?

set name=%CD%
echo %name%

答案 3 :(得分:0)

使用设置命令。

示例:

rem Assign the folder "C:\Folder1\Folder2" to the variable "MySavedFolder"
set MySavedFolder=C:\Folder1\Folder2

rem Run the program "MyProgram.exe" that is located in Folder2
 %MySavedFolder%\MyProgram.exe
rem Run the program "My Second Program.exe" that is located in Folder 2 (note spaces in filename)
"%MySavedFolder%\My Second Program.exe"
rem Quotes are required to stop the spaces from being command-line delimiters, but the command interpreter (cmd.exe) will still substitute the value of the variable.

要删除变量,请不要为名称指定任何内容:

set MySavedFolder=

由于您位于批处理文件中,因此建议在文件末尾使用 setlocal endlocal 来包含变量用法;这使您的环境变量成为批处理文件的本地变量,并且不会污染全局环境名称空间。

答案 4 :(得分:0)

允许脚本确定其父文件夹目录名称:

@echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:\= %
FOR %%a IN (%CDIR%) DO (
  SET CNAME=%%a
)
echo %CDIR%
echo %CNAME%
pause

或者,更好的是:

@echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:~1,-1%
SET CDIR=%CDIR:\=,%
SET CDIR=%CDIR: =_%
FOR %%a IN (%CDIR%) DO SET "CNAME=%%a"
echo %CDIR%
SET CNAME=%CNAME:_= %
echo %CNAME%
pause