无法从批处理脚本中的%%值设置变量 [英] Cannot set variable from %% value inside batch script

查看:442
本文介绍了无法从批处理脚本中的%%值设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此 answer 我正在尝试将%%a%%b值保存到变量中,但是它确实不起作用:

Based from this answer I am trying to save the %%a and %%b values into variables but it does not work:

@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 Created on: %%a, %%b打印正确的信息,echo %vara%, %varb%的输出也为空!我的想法是以后可以操纵该变量,例如提取子字符串.

But the output of the echo %vara%, %varb% is empty even though the previous echo Created on: %%a, %%b prints the correct information!. The idea is that I can manipulate that variable afterwards for example for extracting substrings.

在线搜索后,我发现了这个 answer ,我从中尝试了setlocal ENABLEDELAYEDEXPANSION,和带有感叹号的方法,但它们也失败了.

After searching online, I found this answer from which I tried the setlocal ENABLEDELAYEDEXPANSION, and the approach with the exclamation marks, but they too failed.

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

[UPDATE to include my other attempt and partly fix when using exclamation marks]

@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现在已保存并适当地回显,但是子字符串现在不起作用.

Where the vara and varb are now saved and echoed appropriately but the substring now does not work..

我尝试阅读有关%%变量的详细信息(

I tried reading more about the specifics of a %% variable (link) but that did not help me either.

有什么建议/示例吗?

推荐答案

您的第二个脚本运行完美.我能发现的唯一错误是在此行:set day=%vara:~0,2%.应该是set day=!vara:~0,2!.

Your 2nd script works perfectly. The only error I can spot is in this line: set day=%vara:~0,2%. It should be set day=!vara:~0,2!.

@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. 
)

这篇关于无法从批处理脚本中的%%值设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆