4

I am trying to get the lastmodified date of files which have almost the samename (CompactReg00 in common).

I want this date to be safe to different date settings so I was thinking to use wmic command. The command work well if I use it like that :

set filename=CompactReg00_20200504T112430Z
for /f %%p in ('wmic  DataFile where "name='C:\\Temp\\Alarm\\Archive\\20200508\\sDiag\\%filename%'" get lastmodified   ^| find "+" ') do set "val=%%p"
echo %val%

but when I want to include it to another for loop to get lastmodied date of all "CompactReg00" files I cannot get the %val% value

here is my script:

for /R %%a IN (*CompactReg00*) DO (
        echo %%~na
        for /f %%p in ('wmic  DataFile where "name='C:\\Temp\\Alarm\\Archive\\20200508\\sDiag\\%%~na'" get lastmodified   ^| find "+" ') do set "val=%%p"
        echo %val%
        echo %%~na_%val%
        )

Can you help me to correct it or find another way to get this lastmodified date always yyyymmdd

Compo
  • 36,585
  • 5
  • 27
  • 39
Sirolf
  • 45
  • 4
  • 3
    a [delayed expansion](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected/30284028#30284028) issue. Also useful: [link](https://stackoverflow.com/questions/7727114/batch-command-date-and-time-in-file-name/18024049#18024049) – Stephan May 08 '20 at 15:58
  • If you don't assign `%%p` to a variable but use it immediately, you don't need delayed expansion; of course `echo %%~na_%%p` needs to be inside of the `for /F` loop then, but this doesn't change anything else since it iterates only once anyway... – aschipfl May 08 '20 at 17:26

1 Answers1

2

Refer to link that posted by @Stephan You should use SetLocal EnableDelayedExpansion before the loop for...do and make some tweaks to get the date as yyyymmdd :

@echo off
SetLocal EnableDelayedExpansion
@for /R %%a IN (*CompactReg00*) DO (
    echo "%%~nxa"
    @for /f %%p in ('wmic  DataFile where "name='C:\\Temp\\Alarm\\Archive\\20200508\\sDiag\\%%~nxa'" get lastmodified   ^| find "+" ') do (
        set "val=%%p"
        echo "!val!"
        set "year=!val:~0,4!"
        set "month=!val:~4,2!"
        set "day=!val:~6,2!"
        echo "%%~na_!val!"
        echo !year!!month!!day!
    )
)
pause
Hackoo
  • 18,337
  • 3
  • 40
  • 70