set variable in forfiles in for cycle

纵饮孤独 提交于 2021-02-08 09:51:45

问题


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

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?


回答1:


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.


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

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

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

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



回答2:


You cannot set variables in your batch file from a forfiles call because that one will always spawn a new shell. forfiles is a program, not a built-in command.

However, you can get the modification time with %%tf in your loop, without forfiles:

setlocal enabledelayedexpansion
FOR %%f IN (*.jpg) DO (
    set "fn=%%~tf"
    echo !fn!
)



回答3:


If you need exactly FORFILES, just write output to tempfile:

...
set file=temp.txt
...
FORFILES /M "%%f" /C "cmd /c echo @ftime >> %file%"
FOR /F "usebackq tokens=1,*" %%a In ("%file%") Do (Set fn=%%a | echo %fn%)
DEL %file% /q   


来源:https://stackoverflow.com/questions/34484522/set-variable-in-forfiles-in-for-cycle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!