我正在尝试获取Logs文件夹中最近修改的文件的日期和时间(在变量上),但是我总是遇到错误 [英] I am trying to get the Date and Time (on a variable) of the most recently modified file in the Logs folder but I always get an error

查看:148
本文介绍了我正在尝试获取Logs文件夹中最近修改的文件的日期和时间(在变量上),但是我总是遇到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取Logs文件夹中最近修改的文件的日期和时间(在变量上),但我总是收到错误消息(这时是意外的情况.")

I am trying to get the Date and Time (on a variable) of the most recently modified file in the Logs folder but I always get an error ('was unexpected at this time.')

我正在使用以下代码:

@echo off
SETLOCAL

for /f %%G in ('dir .\Logs /b/a-d/o-d/t:w') do (
    if not defined NewestFileTime (
        set NewestFileTime=%%~tG
    ) else (
        if %NewestFileTime% GTR %%~tG set NewestFileTime=%%~tG
    )
)

if not defined NewestFileTime (
    echo There is no file in current directory.
    goto :exit
)

echo Last file modification time is: %NewestFileTime%

:exit
endlocal
echo.
echo Press CTRL+C to exit
pause

推荐答案

脚本中存在许多重叠的错误:

You have a complex of overlapping bugs in your script:

  • 由于代码块,您需要启用延迟扩展.
  • 您在比较中使用了错误的运算符.
  • 您必须在比较中引用字符串.

当比较字符串(尤其是表示数字的字符串)时,您应该始终意识到的一件事是,该比较是基于您所配置的语言的代码点进行的.所以"2019-1-1" < "2019-01-01"由于字符串的长度不同.但是,如果且仅当它们遵循完整的YYYY-MM-DDhh:mm am|pm格式时,才可以比较使用相同格式的日期/时间字符串.

One thing you should always be aware of, when comparing strings, particularly those that represent numbers, is the comparison is based on the code points of your configured language. So "2019-1-1" < "2019-01-01" due to the the different lengths of the strings. But it is okay to compare date/time strings that use the same format, if and only if they adhere to the full YYYY-MM-DD and hh:mm am|pm formats.

这是您的固定代码:

@echo off
setlocal EnableExtensions EnableDelayedExpansion

for /f %%G in ('dir .\Logs /b/a-d/o-d/t:w') do (
    if not defined NewestFileTime (
        set NewestFileTime=%%~tG
    ) else (
        if "!NewestFileTime!" LSS "%%~tG" set NewestFileTime=%%~tG
    )
)

if not defined NewestFileTime (
    echo There is no file in current directory.
    goto :exit
)

echo Last file modification time is: %NewestFileTime%

:exit
endlocal
echo.
echo Press CTRL+C to exit
pause

在我的系统上对该目录进行了测试:

Tested against this directory on my system:

Directory of D:\TMP\test\Logs

2020-02-04  11:37 AM    <DIR>          .
2020-02-04  11:37 AM    <DIR>          ..
2020-01-16  02:07 AM               135 fqpnTest.cmd
2020-02-04  11:32 AM               578 test.cmd
2020-02-04  11:37 AM                15 test.txt
               3 File(s)            728 bytes

结果是:

> test
Last file modification time is: 2020-02-04 11:40 AM

Press CTRL+C to exit
Press any key to continue . . .

明显的时间差异是由于我的创建时间不等于我的上次更新时间造成的.

The apparent time discrepancy is caused by the fact that my creation times aren't equal to my last update times.

这篇关于我正在尝试获取Logs文件夹中最近修改的文件的日期和时间(在变量上),但是我总是遇到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆