[英]bat script for loop works on CL but does not work when double clicked
I have a batch file and inside the batch file, it looks in a particular directory and saves to a variable, the name of the first directory/file. 我有一个批处理文件,在批处理文件中,它查找特定目录并保存到变量,即第一个目录/文件的名称。 Here is roughly what I am doing:
这大致是我正在做的事情:
FOR /d %%F IN (%INSTALL_DIR%\dir\*) DO (
set NAME=%%~xnF
set NAME_DIR=%INSTALL_DIR%\dir\%NAME%
goto :break
)
When I run this from the command line, it works perfectly and NAME_DIR gets the correct value. 当我从命令行运行它时,它完美地工作,NAME_DIR获取正确的值。 However, when I double-click on the file, the NAME variable is blank.
但是,当我双击该文件时,NAME变量为空。 NANE_DIR is thus set to %INSTALL_DIR%\\dir.
因此,NANE_DIR设置为%INSTALL_DIR%\\ dir。 Why does this happen and what can I do to fix it?
为什么会发生这种情况,我该怎么做才能解决这个问题?
For more clarification, from the command line, this is what NAME and NAME_DIR equal when echoed: 为了更清楚,从命令行,这是回显时NAME和NAME_DIR相等:
NAME: dir1.3.8
NAME_DIR: D:\root\path\to\dir\dir1.3.8
This is what is echoed when double clicked: 这是双击时回显的内容:
NAME:
NAME_DIR: D:\root\path\to\dir
What RaymondChen told me in the comments worked! RaymondChen在评论中告诉我的是什么! I needed to use delayed expansion.
我需要使用延迟扩展。 The reason for this is that windows executes the for loop as one single instruction and so it fills in all the variables at once before executing the for loop.
这样做的原因是windows将for循环作为单个指令执行,因此它在执行for循环之前立即填充所有变量。 Since I never had NAME set before the for loop, it would just evaluate to nothing.
由于我从未在for循环之前设置NAME,因此它只会评估为空。 Therefore NAME_DIR gets an empty string in place of %NAME%.
因此,NAME_DIR获取一个空字符串来代替%NAME%。 I noticed that when I first ran the script on the command line, it did not work.
我注意到,当我第一次在命令行上运行脚本时,它不起作用。 I ran it again and it worked.
我再次运行它,它工作。 I kept running it and it worked every time.
我一直在运行它,每次都有效。 Thats because after running the for loop once, the variable is saved and never changed.
这是因为在运行for循环一次之后,变量被保存并且永远不会改变。 So the next time I run the code, the variable is not blank anymore, it has the correct value.
因此,下次运行代码时,变量不再是空白,它具有正确的值。 Now when double clicking, the NAME variable is null at the beginning.
现在双击时,NAME变量在开头为空。 After the for loop executes, the value of NAME is updated.
执行for循环后,将更新NAME的值。 Once the script executes and the cmd windows exits, the new value of the variable is lost and it starts all over again.
一旦脚本执行并且cmd窗口退出,变量的新值将丢失并重新开始。 Here is the new code with delayed expansion:
这是延迟扩展的新代码:
setlocal ENABLEDELAYEDEXPANSION
FOR /d %%F IN (%INSTALL_DIR%\dir\*) DO (
set NAME=%%~xnF
set NAME_DIR=%INSTALL_DIR%\dir\!NAME!
goto :break
)
I added in the setlocal statement and changed %NAME%
to !NAME!
我在setlocal语句中添加了并将
%NAME%
更改为!NAME!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.