检查文件是否存在时,未执行ELSE条件

问题描述 投票:0回答:3

我有一个批处理脚本,它检查以下有关文件: 1.如果文件存在 2.如果文件为空 3.如果文件是最新的(与当前日期比较)

每当我运行批处理时,我都能获得所有条件的结果,并且我正在使用的文件夹中存在一个文件。但是,当我删除文件然后运行脚本来测试条件#1时,它会退出。

我注意到没有执行检查文件是否存在的条件的ELSE语句。以下是代码:

@echo off  
setlocal   
set strpath="C:\SAMPLE.txt"  
set $strErrorMessage="No Error"  

set datenow=%DATE:~4,13%  
FOR %%A IN (%strpath%) DO set filelastmodifieddate=%%~tA  
FOR %%A IN (%strpath%) DO set filesize=%%~zA  

set filelastmodifieddate=%filelastmodifieddate:~0,10%  

IF EXIST %strpath% (  
   IF %filesize% NEQ 0 (  
      IF %filelastmodifieddate% EQU %datenow% (rem do something  
      ) ELSE (SET strErrorMessage=FILE IS NOT UDPATED)  
   ) ELSE (SET strErrorMessage=ZERO BYTE FILE)  
) ELSE (SET strErrorMessage=FILE DOES NOT EXIST)  

echo %strErrorMessage%
batch-file
3个回答
0
投票
@echo off
setlocal
set "strpath=C:\SAMPLE.txt"
set "strErrorMessage=No Error"

set "datenow=%DATE:~4,13%"

if not exist "%strpath%" (
    set "strErrorMessage=FILE DOES NOT EXIST"
    goto :end
)

for %%A in ("%strpath%") do set "filelastmodifieddate=%%~tA"
for %%A in ("%strpath%") do set "filesize=%%~zA"

set "filelastmodifieddate=%filelastmodifieddate:~0,10%"

if %filesize% EQU 0 (
    set "strErrorMessage=ZERO BYTE FILE"
) else if %filelastmodifieddate% NEQ %datenow% (
    set "strErrorMessage=FILE IS NOT UDPATED"
)

:end
echo(%strErrorMessage%

如果文件不存在,那么做for循环或其他任何东西似乎都是不合逻辑的。因此,如果文件存在,请执行for循环以获取文件的时间戳和大小,否则设置FILE DOES NOT EXISTgoto :end

现在,如果文件存在并且被视为有效,则其余代码可以继续。如果你确实考虑不首先检查文件是否存在,那么你可能会遇到与未定义变量的if比较等语法错误。


1
投票

用这个替换整个if语句块。这是一种稍微简单,更易读的方式来做你想做的事情:

if not exist %strpath% (
     set "strErrorMessage=File does not exist!"
     goto :end
  )
if %filesize% equ 0 (
     set "strErrorMessage=Zero Byte file!"
     goto :end
  ) 
if %filelastmodifieddate% neq %datenow% (
     set "strErrorMessage=File not updated!"
     goto :end
  )
rem If we get to this pint, we have met all the requirements and we DO SOMETHING here
set "strErrorMessage=Success!"

:end
echo %strErrorMessage%

0
投票

即使使用缩进,嵌套条件也不太方便阅读和理解逻辑。如果您重新考虑条件,您将能够简化逻辑,如下所示:

set "strErrorMessage=NO ERROR"

for %%a in ( %strpath% ) do if not exist "%%~a" (
    SET "strErrorMessage=FILE DOES NOT EXIST"
) else if %%~za equ 0 (
    SET "strErrorMessage=ZERO BYTE FILE"
) else if %%~ta neq %datenow% (
    SET "strErrorMessage=FILE IS NOT UDPATED"
)
© www.soinside.com 2019 - 2024. All rights reserved.