简体   繁体   English

从命令窗口执行并双击bat文件时,Windows .Bat文件的行为有所不同

[英]Windows .Bat file behave differently when executed from command window and by double clicking on the bat file

Windows .Bat file behave differently when executed from command window and by double clicking on the bat file. 从命令窗口执行并双击bat文件时,Windows .Bat文件的行为会有所不同。 This is my file: 这是我的文件:

ECHO ON
del activity_ftp.log
cd D:\My_Test
IF EXIST united_ops*.csv (
for %%i in (united_ops*.csv) do (
set size=0
set /A size=%%~zi
echo %%i,%size%,397312,624640 > D:\My_Test\activity_ftp.log
)
)

When I run this by opening command window and calling it, 当我通过打开命令窗口并调用它来运行它时,

There are some issues in your code. 您的代码中存在一些问题。
cd d:\\My_test will only work if you are on D: , you could use cd /d or pushd here. cd d:\\My_test如果你是只会工作D:你可以使用cd /dpushd这里。

echo ...%size% doesn't work, as it's expands when the for block is parsed not when it's executed. echo ...%size%不起作用,因为它在解析for块而不是在执行时会扩展。

The if exist seems to be redundant, as the for %%i in ( united_ops*.csv) only expands if any file exists. if exist似乎是多余的,因为for %%i in ( united_ops*.csv)仅在存在任何文件时才扩展。

ECHO ON
setlocal EnableDelayedExpansion
del activity_ftp.log
pushd D:\My_Test
for %%i in (united_ops*.csv) do (
    set size=0
    set /A size=%%~zi         
    echo %%i,!size!,397312,624640 > D:\My_Test\activity_ftp.log
)

Building on jeb's answer. 建立在jeb的答案上。

1) Your FOR loop may iterate through many files that match your pattern. 1)您的FOR循环可能会遍历许多与您的模式匹配的文件。 But you use the overwrite mode of file redirection. 但是您使用文件重定向的覆盖模式。 Each found file will over-write the output for the prior file. 找到的每个文件都将覆盖先前文件的输出。 Your final output file will never have more than one line. 您的最终输出文件不会超过一行。 You could change to the append mode using >> , but there is a better way. 您可以使用>>更改为追加模式,但是有更好的方法。 It is faster to enclose the entire loop in parentheses and redirect once in overwrite mode using > . 将整个循环括在圆括号中,然后使用>在覆盖模式下重定向一次,这样更快。

2) You are setting size to 0, then setting it to the file size, and then you don't use it after the line is echoed. 2)您将大小设置为0,然后将其设置为文件大小,然后在回显该行之后就不再使用它。 I suspect you don't need the variable at all, so you don't need delayed expansion. 我怀疑您根本不需要该变量,因此您不需要延迟扩展。

3) The file you delete at the top does not include the path information, so it may not be deleting from the correct folder. 3)您在顶部删除的文件不包含路径信息,因此可能无法从正确的文件夹中删除。 Even if it were, it is unnecessary since you are redirecting in overwrite mode anyway. 即使是这样,这也是不必要的,因为无论如何您都将以覆盖模式进行重定向。

4) Instead of changing the current directory you could include the path in the FOR statement. 4)您可以在FOR语句中包含路径,而不是更改当前目录。

ECHO ON
>"D:\My_Test\activity_ftp.log" (
  for %%i in ("d:\My_Test\united_ops*.csv") do (
    echo %%~nxi,%%~zi,397312,624640
  )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM