通过 DOS 命令获取当前文件夹名称?

dja*_*fan 77 windows batch command-line

是否可以使用 DOS 命令获取当前文件夹名称(不是当前目录路径)?如果是这样,如何?

我得到的最接近的是这个,但它没有这样做:

for /f "delims=\" %%a in ("%CD%") do set CURR=%%a
echo.DIR: %CURR%
Run Code Online (Sandbox Code Playgroud)

注意:上述尝试是我试图对字符串进行标记并将最后一个标记设置为 CURR 变量。

Tam*_*man 112

我发现的最短方法:

for %I in (.) do echo %~nxI
Run Code Online (Sandbox Code Playgroud)

或在 .bat 脚本中:

for %%I in (.) do echo %%~nxI
Run Code Online (Sandbox Code Playgroud)

或在 .bat 中使用变量获取值。

for %%I in (.) do set CurrDirName=%%~nxI
echo %CurrDirName%
Run Code Online (Sandbox Code Playgroud)

说明:http : //www.robvanderwoude.com/ntfor.php

nx 仅表示文件名和扩展名

  • 该示例将以交互方式在命令行上运行。要在批处理文件中使用它,您需要用“%%”替换所有出现的“%”。 (3认同)
  • 此外,该示例无法正确处理包含句点 (`.`) 的文件夹名称,例如我的 %USERPROFILE% 文件夹。 (2认同)

Kur*_*fle 35

如果您想知道批处理文件的当前位置(并且如果您的 Windows 不是一个非常古老的版本),请for /?在“DOS 框”窗口中键入。向下滚动。读。

你会发现,你现在可以(从阅读的批处理文件)这些变量:

%0      - as the name how this batchfile was called
%~d0    - as the drive letter where this batchfile is located ('\\' in case of share)
%~p0    - as path (without the drive letter) where this batchfile is located
%~n0    - as filename (without suffix) of this batchfile
%~x0    - as filename's suffix (without filename) of this batchfile
%~a0    - as this batchfile's file attributes
%~t0    - as this batchfile's date+time
%~z0    - as this batchfile's filesize
%~dpnx0 - as this batchfile's fully qualified path+filename
[... and then some more ...]
Run Code Online (Sandbox Code Playgroud)

这适用于许多情况。假设批处理文件名为mytest.bat. 你可以用不同的方式调用它:

  1. ..\..\to\mytest.bat ..................................... (相对路径)
  2. d:\path\to\mytest.bat..................... (完整路径)
  3. \\fileserver\sharename\mytest.bat... (远程共享上的路径)

...并且您将始终在变量中获得正确的值。

  • 好的 - 那么要给我一个“+1”吗? (5认同)
  • @djangofan:所以你说*'哇,有趣的是,你是对的......'*你已经知道的事情?!对于一个对你的知识没有贡献的答案?(你知道,'+1' 是点击 ^-箭头——它不同于 * 将答案设为接受的答案*....) (4认同)

小智 18

我个人喜欢 Toms 的回答,直到它在目录名称中遇到点。给了我一个提示:

for /f "delims=\" %%a in ("%cd%") do echo topmost dir: %%~nxa
Run Code Online (Sandbox Code Playgroud)


小智 6

Tom 的回答很好,但是如果您的目录名称中带有句点(即 wxwidgets-2.9.4),您将只能得到全名。因此,这将输出 wxwidgets-2.9,因为 .4 已被视为扩展名(是的,即使它是目录名!)。

要获得完整的输出名称,您必须将扩展名添加到末尾:

FOR %I IN (.) DO Echo %~nI%~xI
Run Code Online (Sandbox Code Playgroud)

并在批处理文件模式下:

FOR %%I IN (.) DO Echo %%~nI%%~xI
Run Code Online (Sandbox Code Playgroud)

或者当然,在批处理文件中设置一个变量:

FOR %%I IN (.) DO SET CurrentD=%%~nI%%~xI
Run Code Online (Sandbox Code Playgroud)


小智 5

另一种方式是:

set "MyPath=%~dpnx0" & call set "MyPath=%%MyPath:\%~nx0=%%" 
echo MyPath=%MyPath%  
Run Code Online (Sandbox Code Playgroud)

它适用于“。” 和路径名中的空格

它有什么作用?

  1. 将整个文件名 (driveletter-path-filename-extension) 放入MyPathVar

  2. MyPathvar 中删除文件名和扩展名

它也适用于 UNC 路径。如果您需要路径末尾的反斜杠。删除第二个 set 命令中的\after MyPath,例如。

set "MyPath=%%MyPath:%~nx0=%%"
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以将当前目录放入变量中。单线:

set a=%cd%
Run Code Online (Sandbox Code Playgroud)

检查

echo %a%
Run Code Online (Sandbox Code Playgroud)

  • 他要的是当前目录名,而不是整个路径,作为a==cd,你也可以使用%cd%。 (6认同)