无法在批处理脚本中设置%%值的变量

时间:2017-07-06 11:56:39

标签: windows batch-file

基于此answer我试图将%%a%%b值保存到变量中,但它不起作用:

@ECHO OFF
SETLOCAL
set "path_of_folder=C:\folderA\folderB"

if exist "%path_of_folder%" ( 
  echo Path exists.
  for /f "skip=5 tokens=1,2,4 delims= " %%a in (
   'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
    set "dt=%%a"
    echo Created on: %%a, %%b
    set "vara=%%a"
    set "varb=%%b"
    echo %vara%, %varb%

    REM substring
    set day=%vara:~0,2%
  )
) else ( 
  echo Path does not exist. 
)

GOTO :EOF

但即使前一个echo %vara%, %varb%打印出正确的信息,echo Created on: %%a, %%b的输出也是空的!我的想法是,我可以在之后操纵该变量,例如用于提取子串。

在网上搜索后,我发现了answer,我尝试了setlocal ENABLEDELAYEDEXPANSION,并且带有感叹号的方法,但它们也失败了。

[更新以包含我的其他尝试,并在使用感叹号时部分修复]

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

if exist "%path_of_folder%" ( 
  echo Path exists.
  for /f "skip=5 tokens=1,2,4 delims= " %%a in (
   'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
    set "dt=%%a"
    echo Created on: %%a, %%b
    set vara=%%a
    set varb=%%b
    echo !vara!, !varb!

    REM substring
    set day=%vara:~0,2%
  )
) else ( 
  echo Path does not exist. 
)

GOTO :EOF

varavarb现在已保存并适当回显,但子字符串现在不起作用..

我尝试详细了解%%变量(link)的细节,但这对我也没有帮助。

有任何建议/例子吗?

1 个答案:

答案 0 :(得分:1)

你的第二个脚本完美无缺。我能发现的唯一错误就是这一行:set day=%vara:~0,2%。它应该是set day=!vara:~0,2!

enter image description here

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

if exist "%path_of_folder%" ( 
  echo Path exists.
  for /f "skip=5 tokens=1,2,4 delims= " %%a in (
   'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
    set "dt=%%a"
    echo Created on: %%a, %%b
    set vara=%%a
    set varb=%%b
    echo !vara!, !varb!

    REM substring
    set day=!vara:~0,2!
  )
) else ( 
  echo Path does not exist. 
)