简体   繁体   中英

Batch file to loop through a directory and create a variable based on each file

I have a text file with a list of server IP addresses and the code below (which I've scrapped together from other coding) loops through it and brings back a modified date of a named file for each server in the list...

@ECHO On
SETLOCAL
FOR /f %%a IN (C:\Scripts\Servers.txt) DO (
 CALL :getmod %%a
)

GOTO :EOF

:getmod
SET Server=%1
SET File=Abs_Client.exe

FOR %%i IN ("\\%Server%\C$\Com_Dir\%File%") DO SET modif_time=%%~ti
Echo %Server% %File% %modif_time% >> "C:\Scripts\Server_App_Mod_date.txt"

GOTO :eof

That works great...however, what I'd like to do is create another loop around it which creates a variable for each file in a directory and pass that into the code above instead of having to manually change the 'SET File' as shown above for individual files.

Something along the lines of;

@ECHO On
SETLOCAL

FOR /D %VAR IN ("\\Network_Location\AppMedia\App Source Files\Prod Apps\Server_Update") DO (

FOR /f %%a IN (C:\Scripts\Servers.txt) DO (
 CALL :getmod %%a
)

GOTO :EOF

:getmod
SET Server=%1
SET File=%VAR

FOR %%i IN ("\\%Server%\C$\Com_Dir\%File%") DO SET modif_time=%%~ti
Echo %Server% %File% %modif_time% >> "C:\Scripts\Server_App_Mod_date.txt"

GOTO :eof

)

Clearly it's wrong so any ideas/help please?

haven't testet, but maybe a hint in the right direction:

@ECHO ON
SETLOCAL 

FOR /F "TOKENS=*" %%F IN ('DIR "\\Network_Location\AppMedia\App Source Files\Prod Apps\Server_Update" /s /b /a:-d') DO (
  FOR /F %%A IN (C:\Scripts\Servers.txt) DO (
    CALL :getmod %%A "%%~nxF"
  )
)

GOTO :EOF

:getmod
SET Server=%1
SET "tmpFile=%~2"

FOR %%I IN ("\\%Server%\C$\Com_Dir\%tmpFile%") DO ECHO %Server% %tmpFile% %%~tI >> "C:\Scripts\Server_App_Mod_date.txt"
GOTO :EOF

As far as i know, FOR /D only executes for directorys and if i understand your question, you have files in "Prod Apps\\Server_Update", for each you like to have the file-date/time from the target-server... right?

Edit:

Maybe this works too:

FOR /F "TOKENS=*" %%F IN ('DIR "\\Network_Location\AppMedia\App Source Files\Prod Apps\Server_Update" /s /b /a:-d') DO (
  FOR /F %%A IN (C:\Scripts\Servers.txt) DO (
    FOR %%X IN ("\\%%A\C$\Com_Dir\%%~nxF") DO ECHO %%A %%~nxF %%~tX >> "C:\Scripts\Server_App_Mod_date.txt"
  )
)

without the :getmod

Edit: /b-switch was missing from the first DIR-Command in 2nd suggestion

@ECHO On
SETLOCAL
FOR /f %%a IN (C:\Scripts\Servers.txt) DO (
 FOR /f "delims=" %%i IN ('dir /b/a-d "\\%%a\C$\Com_Dir\*"') DO Echo %%a %%i %%~ti >> "C:\Scripts\Server_App_Mod_date.txt"
)
GOTO :EOF

Should work, IIUC. Can't test, I'm afraid...

[Edit - removed call to getmod - not required]

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