简体   繁体   中英

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

echo ...%size% doesn't work, as it's expands when the for block is parsed not when it's executed.

The if exist seems to be redundant, as the for %%i in ( united_ops*.csv) only expands if any file exists.

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.

1) Your FOR loop may iterate through many files that match your pattern. 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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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