从批处理文件中的路径获取文件夹名称。没有解决

时间:2014-09-01 09:08:59

标签: windows batch-file directory dos

我有这条路径:C:\dev\app\tomcat\apache-tomcat-base作为变量copyFile存储在批处理文件中。

我使用以下代码尝试获取apache-tomcat-base(文件夹名称)作为新变量copyfolderName

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

然而copyFolderName结束为空。

注意:永远不会输入循环

取自此片段:

:: 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不打印任何内容

3 个答案:

答案 0 :(得分:3)

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

当cmd解析器读取一行或一行(括号内的代码)时,所有变量读取都将替换为变量中的值开始执行代码之前。如果块中代码的执行会更改变量的值,则无法从同一块内部看到此值,因为变量的读取操作不存在,因为它已替换为变量中的值。

要解决此问题,您需要启用延迟扩展,并在需要时将语法从%var%更改为!var!,向解析器指示读取操作需要延迟执行命令。

答案 1 :(得分:0)

添加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

Cheer,G

答案 2 :(得分:0)

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

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