2014-09-01 149 views
1

我有這樣的路徑: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% 
) 

基本名稱打印什麼

+0

'注意:循環永遠不會被輸入'?但是在循環中你得到文件夾名稱的地方?或者有我丟失的東西... – npocmaka 2014-09-01 09:17:31

+0

。 如果我在for循環中添加echo,它永遠不會被調用。 – mangusbrother 2014-09-01 09:18:04

+0

可能你需要添加整個代碼。問題不在上面的摘錄中。 – npocmaka 2014-09-01 09:19:20

回答

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

當CMD解析器讀取線或塊行(括號內的代碼)中,所有變量讀取都被替換爲變量內的值,然後開始執行exec代碼。如果塊中代碼的執行更改了變量的值,則無法在同一個塊內看到該值,因爲該變量的讀取操作不存在,因爲它已用變量中的值替換。

要解決該問題,您需要啓用延遲擴展,並在需要時將語法從%var%更改爲!var!,指示解析器讀取操作需要延遲至執行命令。

+1

+1,剛剛被回答:-) – npocmaka 2014-09-01 09:28:02

+0

工作像一個魅力 – mangusbrother 2014-09-01 09:31:11

+0

@npocmaka,我知道它是如何:-)通常我開始打字,並在做這件事時,我終於看到如何foxidrive張貼相同或更好的解決方案。 – 2014-09-01 09:34:45

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 

歡呼,G

+0

在新的命令提示符會話中嘗試它:-) – npocmaka 2014-09-01 09:51:48

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! 
) 
相關問題