在for周期中的forfiles中设置变量 [英] set variable in forfiles in for cycle

查看:55
本文介绍了在for周期中的forfiles中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Echo On
FOR %%f IN (*.jpg) DO (
    forfiles /M "%%f" /C "cmd /V:ON /c set fn=@ftime"
    echo %%fn%%
)
pause

我想在 FOR 循环中获取 @ftime ,但这不起作用.也许还有另一种方法来获取文件的修改时间?

I want to get @ftime in FOR loop, but this isn't working. Maybe there is another way to get modify time of the file?

推荐答案

在您的方法中,您正在 cmd 实例中设置由 forfiles ,但是在运行脚本的 cmd 实例中该变量不再可用.

In your method, you are setting a variable fn within the cmd instance that is opened by forfiles, but this variable is no longer available in the cmd instance that runs your script.

您可以使用 for 变量的〜t 修饰符(因此在代码中为 %%〜tf )来获取修改日期和时间,然后,如果分钟的特征分辨率足够("%%〜nxF" 部分),则通过子字符串扩展将时间部分拆分(请参见 set/?)在返回的时间之前加上当前文件名):

You can use the ~t modifier of the for variable (so %%~tf in your code) to get the modification date and time, then split off the time portion by substring expansion (see set /?), if the featured resolution of minutes is sufficient (the "%%~nxF" portion just precedes the returned time with the current file name):

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for %%F in ("*.jpg") do (
    set "FTIME=%%~tF"
    rem The following line depends on region settings:
    echo "%%~nxF": !FTIME:~11!
)
endlocal
pause

或者,您可以使用 for/F 循环从日期中分离时间部分:

Alternatively, you can use a for /F loop to split off the time part from the date:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%F in ("*.jpg") do (
    for /F "tokens=1,* delims= " %%I in ("%%~tF") do (
        echo "%%~nxF": %%J
    )
)
endlocal
pause


如果需要 forfiles 支持的秒分辨率,则需要在 forfiles 中回显 @ftime 值并通过/F 的循环,每个循环(时间)仅迭代一次( @file 返回当前文件名,然后由"%%〜K"):


If you require a resolution of seconds as supported by forfiles, you need to echo the @ftime value within forfiles and capture that by a for /F loop, which iterates once only per each file (time) (@file returns the current file name, which is then held by "%%~K"):

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%F in ("*.jpg") do (
    for /F "tokens=1,* delims=|" %%K in ('
        forfiles /M "%%~F" /C "cmd /C echo @file^|@ftime"
    ') do (
        echo "%%~K": %%L
    )
)
endlocal
pause


根据您的应用程序,您可能不需要单独的 for 循环来遍历 *.jpg 文件,因为 forfiles 可以做到这一点独自:


Depending on your application, you might not need a separate for loop to walk through *.jpg files, because forfiles could do that on its own:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "tokens=1,* delims=|" %%K in ('
    forfiles /M "*.jpg" /C "cmd /C echo @file^|@ftime"
') do (
    echo "%%~K": %%L
)
endlocal
pause

这篇关于在for周期中的forfiles中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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