批处理变量在执行时不扩展

时间:2017-07-19 21:11:29

标签: windows batch-file

我正在为我的IT部门编写一个小型库存脚本,并且在尝试节省一些时间时遇到了一些绊脚石。

我的目标是将当前位置存储在临时本地文件中(此批处理文件将在闪存驱动器上运行),这样当我从一台计算机移动到另一台计算机时,我只需更改位置(如果是不准确。基本上这样,如果我从单元1,A楼,3号房开始,我只需要确认什么是正确的,并改变不正确的。

也许位置确认代码可以让您更好地了解这里发生了什么。

@echo off
setlocal
setlocal EnableDelayedExpansion
if not exist location.tmp (
    echo  , , > location.tmp
)
for /f "tokens=1-3 delims=," %%i in (location.tmp) do (
    if not "%%i" == " " (
        set unit=%%i
    )
    if not "%%j" == " " (
        set building=%%j
    )
    if not "%%k" == " " (
        set room=%%k
    )
)
for %%i in (unit,building,room) do (
    call :SUB_GET %%i
)
echo !unit!,!building!,!room!> location.tmp
endlocal
exit /b 0

:SUB_GET
if not defined %1 (
    set /p %1=What %1? 
    goto :EOF
)
set /p new%1=What %1? (default is !%1!) 
if not "!new%1!" == "" (
    set %1=!new%1!
)

一切正常,除非我尝试允许它保持默认值。我希望能够在值正确时点击输入(例如“什么房间?(默认为403)”点击输入然后保持403)

问题是,当我这样做时,即使代码检查新的环境变量(输入)以查看它是否为空,它仍然会为旧变量分配新变量的值(空字符串)。 / p>

更令人困惑的是,如果我使用默认值(如1,A,4)创建现有的location.tmp并按Enter键确认每个,批处理语句echo !unit!,!building!,!room!>location.tmp执行,但location.tmp保持不变

有什么想法在这里发生了什么?

2 个答案:

答案 0 :(得分:2)

set /p %1=What %1? (default is !%1!) 

如果您只是回复 Enter set /p,那么变量将保持不变。

所以 - 不需要new%1 - 即使那时new已经足够了,因为没有明显需要newROOM等等。你必须明智地清除new避免保留过时的数据。

答案 1 :(得分:0)

echo !unit!,!building!,!room!>location.tmp中变量的延迟执行导致它们过于扩展,因此语句无论出于何种原因都无法正确执行。用普通%变量%替换它们可以解决这两个问题。事实证明比较工作正常,只是没有及时扩展。

编辑:不知道为什么,但上述内容不正确。以下脚本完美无缺......

@echo off
setlocal
setlocal EnableDelayedExpansion
if not exist location.tmp (
    echo  , , > location.tmp
)
for /f "tokens=1-3 delims=," %%i in (location.tmp) do (
    if not "%%i" == " " (
        set unit=%%i
    )
    if not "%%j" == " " (
        set building=%%j
    )
    if not "%%k" == " " (
        set room=%%k
    )
)
for %%i in (unit,building,room) do (
    call :SUB_GET %%i
)
echo !unit!,!building!,!room!> location.tmp
endlocal
exit /b 0

:SUB_GET
if not defined %1 (
    set /p %1=What %1? 
    goto :EOF
)
set /p %1=What %1? (default is !%1!)