从batch file中的path获取文件夹名称。 没有解决

我有这样的path:作为variablescopyFile存储在一个batch file中的C:\dev\app\tomcat\apache-tomcat-base

我正在使用下面的代码尝试获取apache-tomcat-base (文件夹名称)作为新variablescopyfolderName

 for /f "delims=" %%F in ("%copyFile%") do ( set copyfolderName=%%~nxF ) 

然而copyFolderName结尾是空的。

注意:循环永远不会被input

采取从这个片断:

 :: Check if the file to be copied is a directory of file. If a directory define %isDirect% IF exist "%copyFile%\" set isDirect=directory :: Copy folder with all contents IF defined isDirect ( ::Get name of folder for the copyingDirectory folder for /f "delims=" %%F in ("%copyFile%") do ( echo setting %%~nxF set copyfolderName=%%~nxF ) echo BASE NAME: %copyfolderName% ) 

BASE NAME不打印任何东西

 .... setlocal enabledelayedexpansion echo BASE NAME: !copyfolderName! endlocal .... 

当cmd解析器读取一行或一行代码块(括号内的代码)时, 开始执行代码之前 ,所有变量读取都将用变量内的值替换。 如果程序段中的代码的执行改变了变量的值,则该值不能在同一块内部看到,因为变量的读取操作不存在,因为它被变量中的值取代。

为了解决这个问题,你需要启用延迟扩展,并根据需要将语法从%var%更改为!var! ,向解析器指示读操作需要被延迟直到执行命令。

添加setlocal enabledelayedexpansion将解决这个问题(我在下面的代码中使用了一个测试文件夹) –

 :: Check if the file to be copied is a directory of file. If a directory define %isDirect% @echo off set "copyfile=c:\drivers\test folder" IF exist "%copyFile%\" set isDirect=directory :: Copy folder with all contents setlocal enabledelayedexpansion IF %isDirect% equ directory ( ::Get name of folder for the copyingDirectory folder for /f "delims=" %%F in ("%copyFile%") do ( echo setting %%~nxF set copyfolderName=%%~nxF ) echo BASE NAME: %copyfolderName% ) 

测试输出 –

 D:\Scripts>draft.bat setting test folder BASE NAME: test folder 

欢呼,G

如果你想这样做,考虑一下:

 setlocal EnableDelayedExpansion IF exist "!copyFile!" ( set isDirect=directory for /f %%F in ("!copyFile!") do ( echo setting %%~nxF set copyfolderName=%%~nxF ) echo BASE NAME: !copyfolderName! )