List files by name (containing date), but filter the 5 days prior to the current date with . bat?

Asked

Viewed 3,721 times

13

I’m trying to do something that maybe it’s not even possible to do in but specific using findstr?

I have a dozen files in that layout: filename

So, date as day and month content two digits and year with four digit, file name and date format contain underline, days and months smaller than 10 contain 0 in front.

I need the script that could catch at least the day in the file name.

Obs.: I’ve already been able to get by the modification date but in this case I need the date that is in the file name.

Also/, I need to generate a.log file or an alert warning informing the files that would be out of date with a 5-day limit before the current date.

Something like this is possible using ?

  • good morning, yes has underline between(*filename)(year)(month)day(time) and at the time no dots or dashes or underline would be together!

  • show what you’ve done..., put an example of the line you want to treat, is much easier to understand than reading an explanation of the line format, and put an example of the log line you want to have

  • 1

    Of course it is possible to do it in bat - but it is the kind of problem that is best solved in a higher-level language that has a better separation between data and command parameters. The same problem in Python, for example, would be solved by a program that would be much more readable and smaller. Probably in visual basic as well

  • 2

    I don’t understand, everything is solved with high-level language, no doubt, why not delete :as tags: cmd/bat/batch/script/etc... Why are questions accepted and not closed? It is not the case to solve the problem, it is the case of thus solve the problem.

  • 3

    @jsbueno o o op specified .bat. If we start to choose the language and the system in which we will give the answers all questions will have to be closed because they are too broad or because they are subjective because for example I do not think that in Python if you get a good answer I believe that in PHP I get a higher response than Python. Then soon after will arise another op who will claim that in Java a higher response is achieved thus eliminating the need for tags.

  • 3

    I understand to have in bat a difficulty that is not recognized, personal uses the powershel, yes, it is easier, yes, it has infinite resources, yes, but ignore, do not recognize, the difficulty that is to respond using a command interpreter with its limitations.

Show 1 more comment

4 answers

23



Yes, you can get the dates and names of the files previous 05 days previous date via bat/cmd:

  1. Reads the date system and turn into numbers: 2019/01/01 = 20190101

  2. That number subtraction the number of date - 05 days: 20190101-20181227=8874

  3. We do the same with all months obtaining the days to be subtracted month by month

  4. Dai filtering via for looping whatever less/equal to 05 and greater/equal to 06

  5. We used a loop for (4 + 2020 to 2100), for compare if the current year is leap

  6. Num array: Mês=_i Dias_Subtrair=_j set _m_d=01-8874,02-75,03-!_f!..

  7. As month-day variables compared with the position %%i-%%j, gives how much subtract

  8. Hence, if the day is less than 06, subtract the %%j, but, subtract 1

Remarks:

  1. Log file. will be servant in the briefcase %temp% and moved briefcase !_path_pdf!

  2. Content of log file. will be copied to your Ctrl+c

  3. Edit the command: Set "_path_pdf=."
    Substituting the value: =. for =drive:\pasta\onde\tem\os\pdfs
    So that it stays: set "_path_pdf=drive:\pasta\onde\tem\os\pdfs"


Script -05_days.cmd:


@echo off && setlocal enableextensions enabledelayedexpansion 

rem :: Edite variavel _path_pdf substituindo por drive/pasta/dos/seus/pdf's ::
cd /d "%~dp0" && set "_path_pdf=." && cd /d "!_path_pdf!"

rem :: Compondo string para uso com findstr onde verifica ano atual/bisexto ::
for /l %%l in (2020 4 2100)do set _b6to=!_b6to!%%l,
set "_do=wmic Path Win32_LocalTime Get Day^,Month^,Year" 

rem :: Obtendo a data com layout previsível e sem possível customização do usurario :: 
for /f "tokens=1-3delims= " %%a in ('!_do!^|findstr /r [0-9]')do ( 
     set "_y=%%c" & set "_dd=0%%a" & set "_mm=0%%b" & set "_m=!_mm:~-2!" 
     set "_d=!_dd:~-2!" & set "_dt=!_y!_!_m!_!_d!" & set "_dt_str=!_y!!_m!!_d!"
    ) && set /a "_loop=1!_d!-101" & set "_cnt=0" & set "_log=%temp%\!_dt!.log"

rem :: Compondo um "pseudo" array para uso em alguns loopings for junto call :^[  ::
rem :: Observando que o 01 = mes c 2 digitos e o 8875, são os dias para subtrair  ::
rem :: os dias/datas pregressas tratadas como mumeros. 20190105 -8875 = 20181231  ::
rem :: Procurando ano bisexto na string com findstr para verificar se ano bisexto ::
echo/!_b6to!|findstr /lic:"!_y!,">nul && set /a "_f=77" || set /a "_f=78"
set "_m_d=01-8874,02-75,03-!_f!,04-75,05-76,06-75,07-76,08-75,09-75,10-75,11-75,12-76"

rem :: Identificando mes/dias quantitativos para subtrair na data atual -05 dias ::
for %%~ in (!_m_d!)do for /f "tokens=1,2delims=-" %%i in ('echo/%%~')do ( 
     if 1!_d! gtr 105 if /i [%%i] equ [!_m!] call :^] %%j "5 -1 1" 5 & goto :^)
     if 1!_d! leq 105 if /i [%%i] equ [!_m!] call :^] %%j "1 +1 5" 1 & goto :^)
    )

:^]
rem :: 1) Datas sendo subtraidas para obter intervalo de 05 dias anteriores a !_dt! ::
rem :: 2) Compondo layout/pattern do intervalo de datas e buscas dos Arquivos .PDFs ::
rem :: 3) Buscando e registrando resultados obtidos no Arquivo log %temp%\!_dt!.log ::
echo/Listagem do^(s^) Arquivo^(s^) Desatualizados em !_dt:_=/!:>"!_log!" && for /l %%l in (%~2)do (
     if %%l leq !_loop! (set /a "_d[%%l]=!_dt_str!-%%l") else (set /a "_d[%%l]=!_dt_str!-%1" & set /a "_dt_str+=1")
     set "_str_%%l=!_d[%%l]!" & call set "_str_%%l=*_!_str_%%l:~,4!_!_str_%%l:~4,2!_!_str_%%l:~-2!_*.pdf"
     if /i exist ".\!_str_%%l!" where .:"!_str_%%l!">>!_log!
    )
rem :: 4) Listando os resultados das acoes e portando dados p/ crtl+c/ctrl+v e tela ::
for /f "tokens=*delims=:" %%i in ('type "!_log!"^|find /c ".pdf"')do set "_cnt=%%i"
>> !_log! echo/Total de Arquivo^(s^) Desatualizado^(s^): !_cnt! && type "!_log!" | clip
>nul move /y "!_log!" . && exit /b 

:^)
type ".\!_dt!.log" && endlocal & goto :eof

Upshot:

inserir a descrição da imagem aqui


Using a bat that changes the date several times and testing the saturdays/days:

Administrator credential required

Obs.: The for in the date format of my system, check yours by cmd: date <nul|find "("

If necessary change in (10-01-2018 12-05-2018 21-05-2018 05-01-2019 01-10-2019 05-12-2019) changing to your system compliance.

@echo off && setlocal enableextensions enabledelayedexpansion 
mode con cols=60 lines=15 & title SO_pt-BR_Q376119 
rem :: data no formato yyyy-mm-dd, apenas altere para o layout de seu sistema: 
for %%i in (10-01-2018 12-05-2018 21-05-2018 05-01-2019 01-10-2019 05-12-2019)do (
    >nul date %%i 
    echo/Data em !date! & call :SO_pt-BR_Q376119
    )
:SO_pt-BR_Q376119
@echo off && setlocal enableextensions enabledelayedexpansion 
set "_pdf_folder=." && cd /d "!_pdf_folder!"
for /l %%l in (2020 4 2100)do set _b6to=!_b6to!%%l,
set "_do=wmic Path Win32_LocalTime Get Day^,Month^,Year"
for /f "tokens=1-3delims= " %%a in ('!_do!^|findstr /r [0-9]')do ( 
     set "_y=%%c" & set "_dd=0%%a" & set "_mm=0%%b" & set "_m=!_mm:~-2!" 
     set "_d=!_dd:~-2!" & set "_dt=!_y!_!_m!_!_d!" & set "_dt_str=!_y!!_m!!_d!"
    ) && set /a "_loop=1!_d!-101" & set "_cnt=0" & set "_log=%temp%\!_dt!.log"
echo/!_b6to!|findstr /lic:"!_y!,">nul && set /a "_f=77" || set /a "_f=78"
set "_m_d=01-8874,02-75,03-!_f!,04-75,05-76,06-75,07-76,08-75,09-75,10-75,11-75,12-76"
for %%~ in (!_m_d!)do for /f "tokens=1,2delims=-" %%i in ('echo/%%~')do ( 
     if 1!_d! gtr 105 if /i [%%i] equ [!_m!] call :^] %%j "5 -1 1" 5 & goto :^)
     if 1!_d! leq 105 if /i [%%i] equ [!_m!] call :^] %%j "1 +1 5" 1 & goto :^))
:^]
echo/Listagem do^(s^) Arquivo^(s^) Desatualizados em !_dt:_=/!:>"!_log!" && for /l %%l in (%~2)do (
    if %%l leq !_loop! (set /a "_d[%%l]=!_dt_str!-%%l") else (set /a "_d[%%l]=!_dt_str!-%1" & set /a "_dt_str+=1")
    set "_str_%%l=!_d[%%l]!" & call set "_str_%%l=*_!_str_%%l:~,4!_!_str_%%l:~4,2!_!_str_%%l:~-2!_*.pdf"
    if /i exist ".\!_str_%%l!" where .:"!_str_%%l!">>!_log!
    )
for /f "tokens=*delims=:" %%i in ('type "!_log!"^|find /c ".pdf"')do set "_cnt=%%i"
>>!_log! echo/Total de Arquivo^(s^) Desatualizado^(s^): !_cnt! |clip  & exit /b 

:^)
type "!_log!" & timeout /t 7 >nul & cls & endlocal && exit/b

Upshot:

inserir a descrição da imagem aqui


Update - For those interested in reward

Below a pdf file generator that obey the layout of the question.

Remarks:

  1. To generate in previous years just change the date on the system to desired year

  2. Generates files in mode .txt renamed p .pdf of 2019-01-01 until 2019-12-31

  3. After generating the files it is possible to test the outputs of the posted answers.

Script gera_pdf.cmd:

@echo off && setlocal enableextensions enabledelayedexpansion 

set "_do=wmic Path Win32_LocalTime Get Day^,Month^,Year" & for /l %%l in (2020 4 2100)do set "_leap=!_leap!%%l,"
for /f "tokens=1-3delims= " %%a in ('!_do!^|findstr /r [0-9]')do set "_y=%%c" & set "_dd=0%%a" & set "_mm=0%%b"
set "_m=!_mm:~-2!" && set "_d=!_dd:~-2!" && set "_dt=!_y!_!_m!_!_d!" && set /a "_l=!_mm:~1!-1" && set /a "_int=0"
echo/!_leap!|findstr /lic:"!_y!," >nul && (set /a _f=2, _fev=29, _ano=366) || (set /a _f=3, _fev=28, _ano=365) 
set "_m_d=01-31,02-!_fev!,03-31,04-30,05-31,06-30,07-31,08-31,09-30,10-31,11-30,12-31" & set "_log=%temp%\!_dt!.log"
set "_i=-1" & set "_soma=# 0 !_f! 0 1 0 1 0 0 1 0 1 0" & call set "_soma=!_soma!" && set "_soma=%_soma: ="
set /a _i+=1&set "_soma!_i!=%" && set /a _soma=0, _alvo=0&& for /l %%S in (0 1 !_l!)do if not "%%S" == "!_l!" (set /a "_soma+=%%S") else set /a _cnt=%%S * 31 - !_soma!
call set /a "_alvo=!_cnt! + !_dd:~1! - 6" && set "_p=!_dd:~1!" & set /a "_cnt+=!_p!" & for %%I in (!_m_d!)do (
for /f "tokens=1,2delims=-" %%i in ('echo/%%I')do for /l %%x in (1 1 %%j)do set /a "_int+=1" & (
     if %%x leq 9 (set "_x=%%i_0%%x" & set "_a=0%%x!_a!") else (set "_x=%%i_%%j" & set "_a=%%x!_a!")
     call set _random=%random% && call echo/where .:*_!_y!_%%i_!_a:~0,2!_!_x:_=!.pdf >"!_random: =!_!_y!_%%i_!_a:~0,2!_%%i%%j.pdf"
     ))
) 

- - -

Update: without comments and ported to files of any length, only and use the variable set _ext=pdf, exchanging the value pdf by the desired length, noting not to use "." in the variable.


@echo off && setlocal enableextensions enabledelayedexpansion

set "_ext=pdf" & set "_do=wmic Path Win32_LocalTime Get Day^,Month^,Year" 
cd /d "%~dp0" && set "_path_pdf=." && cd /d "!_path_pdf!" 
for /l %%l in (2020 4 2100)do set _b6to=!_b6to!%%l,
for /f "tokens=1-3delims= " %%a in ('!_do!^|findstr /r [0-9]')do ( 
     set "_y=%%c" & set "_dd=0%%a" & set "_mm=0%%b" & set "_m=!_mm:~-2!"
     set "_d=!_dd:~-2!" & set "_dt=!_y!_!_m!_!_d!" & set "_dt_str=!_y!!_m!!_d!"
    ) && set /a "_loop=1!_d!-101" & set "_cnt=0" & set "_log=%temp%\!_dt!.log"  
echo/!_b6to!|findstr /lic:"!_y!,">nul && set /a "_f=77" || set /a "_f=78"
set "_m_d=01-8874,02-75,03-!_f!,04-75,05-76,06-75,07-76,08-75,09-75,10-75,11-75,12-76"
for %%~ in (!_m_d!)do for /f "tokens=1,2delims=-" %%i in ('echo/%%~')do (
     if 1!_d! gtr 105 if /i [%%i] equ [!_m!] call :^] %%j "5 -1 1" 5 & goto :^)
     if 1!_d! leq 105 if /i [%%i] equ [!_m!] call :^] %%j "1 +1 5" 1 & goto :^)
    )
:^]
echo/Listagem do^(s^) Arquivo^(s^) Desatualizados em !_dt:_=/!:>"!_log!" && for /l %%l in (%~2)do (
     if %%l leq !_loop! (set /a "_d[%%l]=!_dt_str!-%%l") else (set /a "_d[%%l]=!_dt_str!-%1" & set /a "_dt_str+=1")
     set "_str_%%l=!_d[%%l]!" & call set "_str_%%l=*_!_str_%%l:~,4!_!_str_%%l:~4,2!_!_str_%%l:~-2!_*.!_ext!" 
     if /i exist ".\!_str_%%l!" where .:"!_str_%%l!">>!_log!
    )
for /f "tokens=*delims=:" %%i in ('type "!_log!"^|find /c ".!_ext!"')do set "_cnt=%%i"
>> !_log! echo/Total de Arquivo^(s^) Desatualizado^(s^): !_cnt! && clip <"!_log!"
>nul move /y "!_log!" . & exit /b 

:^)
type ".\!_dt!.log" && endlocal & goto :eof

  • 2

    This answer is the correct one for question. It was made in CMD as op specified and really search for outdated files.

  • 1

    Log the files of the last 5 days, not the previous month/year etc..

  • 4

    https://pt.meta.stackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas

  • Hello @Itwasn'tme, I tried to improve your edition, if you think it got weird or any other reason, you can enter at this link is to click reverse =P

  • @Icaromartins, It is the first time that any operated edits a reply from me, thank you, is like this!

  • 1

    @Itwasn'tme to adapt this script to search for files whose extensions are different to . pdf is just to modify where you have . pdf and replace to the desired extension as for example the same formatted and etc porem . FDB as would be ?

  • @Walisson Good night, edited to suit any extension, for this just edit the variable _ext!! Without the • (dot)!!

  • @Itwasn'tme ok had not realized that he had made it explicit at the beginning of his explanation ... taking advantage of the cue , to search in subdirectories what would need to be changed ? 'Cause that way you can only see in directories.

  • @Walisson Good night Change where you are: Where .: for Where /r . on line 20 of the first code in the post, it will look like this: where /r . "!_str_%%l!" >>"!_log!"

  • @Walisson I posted in the doubt if you had seen or not, then I commented...

Show 5 more comments

7

This question is interesting as challenge, in practice it is totally unfeasible, the script is complicated and very easy to break.

Update: missing consistency of file names, whether year, month and day of the month are valid.

Here’s a solution I created, for the challenge:

@echo off

:: -----------------------------------------------------------------------------

:: dias do mes - ano nao bissexto

set mes_1_n=31
set mes_2_n=28
set mes_3_n=31
set mes_4_n=30
set mes_5_n=31
set mes_6_n=30
set mes_7_n=31
set mes_8_n=31
set mes_9_n=30
set mes_10_n=31
set mes_11_n=30
set mes_12_n=31

:: -----------------------------------------------------------------------------

:: dias do mes - ano bissexto

set mes_1_b=31
set mes_2_b=29
set mes_3_b=31
set mes_4_b=30
set mes_5_b=31
set mes_6_b=30
set mes_7_b=31
set mes_8_b=31
set mes_9_b=30
set mes_10_b=31
set mes_11_b=30
set mes_12_b=31

:: -----------------------------------------------------------------------------

:: pega data de hoje no formato d/m/a
set data_hoje=%date%

:: separa data_hoje em dia mes ano
for /f "delims=/ tokens=1,2,3" %%a in ("%data_hoje%") do (
  set DIA_HOJE=%%a
  set MES_HOJE=%%b
  set ANO_HOJE=%%c
)
:: echo ano_hoje=[%ANO_HOJE%] mes_hoje=[%MES_HOJE%] dia_hoje=[%DIA_HOJE%]

:: verifica se o ano atual e` bissexto (para fazer a contagem dos dias do ano)
call :VER_SE_ANO_BISSEXTO ANO_BISSEXTO_HOJE %ANO_HOJE%
:: echo ANO_BISSEXTO_HOJE=%ANO_BISSEXTO_HOJE%

:: calcula o dia do ano hoje
call :DIAS_ANO %ANO_HOJE% %MES_HOJE% %DIA_HOJE% %ANO_BISSEXTO_HOJE% DIAS_ANO_HOJE

:: -----------------------------------------------------------------------------

:: filtra nomes de arquivos
dir /b | findstr /r "[^_]*_[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9].pdf" > nomes_validos.txt

:: separa por dia mes ano, e processa cada nome de arquivo
for /f "delims=_ tokens=1,2,3,4,5" %%e in (nomes_validos.txt) do (
  rem echo nome=%%e ano=%%f mes=%%g dia=%%h
  call :PROCESSA_ARQ %%e %%f %%g %%h %%i
)

goto :EOF

:: -----------------------------------------------------------------------------

:PROCESSA_ARQ

set _NOME=%1
set _ANO=%2
set _MES=%3
set _DIA=%4
set _HORA=%5

set _NOME_COMPLETO=%_NOME%_%_ANO%_%_MES%_%_DIA%_%_HORA% 
echo processando %_NOME_COMPLETO%

:: verifica se ano do arquivo e` bissexto, deixa resultado na variavel ANO_BISSEXTO_ARQ
call :VER_SE_ANO_BISSEXTO ANO_BISSEXTO_ARQ %_ANO%
:: echo ANO_BISSEXTO_ARQ=%ANO_BISSEXTO_ARQ%

:: calcula dias do ano
:: echo -- %_ANO% / %_MES% / %_DIA% / %ANO_BISSEXTO_ARQ% / DIAS_ANO_ARQ
call :DIAS_ANO %_ANO% %_MES% %_DIA% %ANO_BISSEXTO_ARQ% DIAS_ANO_ARQ
:: echo @@@ _ANO=%_ANO% ANO_HOJE=%ANO_HOJE% DIAS_ANO_HOJE=%DIAS_ANO_HOJE% DIAS_ANO_ARQ=%DIAS_ANO_ARQ%

if %_ANO% neq %ANO_HOJE% goto :PROCESSA_ARQ_OLD

set /a DIF_DIAS=DIAS_ANO_HOJE-DIAS_ANO_ARQ
:: echo === DIAS_ANO_HOJE=%DIAS_ANO_HOJE% DIAS_ANO_ARQ=%DIAS_ANO_ARQ% %DIF_DIAS%
if %DIF_DIAS% gtr 5 (
  echo !!! %_NOME_COMPLETO% esta' desatualizado
) else (
  echo *** %_NOME_COMPLETO% esta' atualizado
)
goto :EOF

:PROCESSA_ARQ_OLD

:: echo old

set /a _DIF_ANOS=ANO_HOJE-_ANO
:: echo @@@ ANO_HOJE=%ANO_HOJE% ANO=%_ANO% _DIF_ANOS=%_DIF_ANOS%
if %_DIF_ANOS% gtr 1 (
  echo !!! %_NOME_COMPLETO% esta' desatualizado
  goto :EOF
)

set /a DIF_DIAS_ARQ=365-%DIAS_ANO_ARQ%
if %ANO_BISSEXTO_ARQ%==1 (set /a DIF_DIAS_ARQ+=1)

set /a DIF_DIAS_ARQ+=DIAS_ANO_HOJE

if %DIF_DIAS_ARQ% gtr 5 (
  echo !!! %_NOME_COMPLETO% esta' desatualizado
) else (
  echo *** %_NOME_COMPLETO% esta' atualizado
)

goto :EOF

:: -----------------------------------------------------------------------------


:: https://stackoverflow.com/questions/35157817/batch-file-leap-year

:VER_SE_ANO_BISSEXTO

set _NOME_VAR=%1
set _ANO=%2

set /A "_BISSEXTO=!(_ANO%%4) + (!!(_ANO%%100)-!!(_ANO%%400))"
if %_BISSEXTO% equ 1 (set %_NOME_VAR%=1) else (set %_NOME_VAR%=0)

goto :EOF

:: -----------------------------------------------------------------------------

:DIAS_ANO

set _ANO=%1
set _MES=%2
set _DIA=%3
set _ANO_BISSEXTO=%4

:: echo _ANO=%_ANO%
:: echo _MES=%_MES%
:: echo _DIA=%_DIA%

:: nome da variavel que vai conter o resultado
set _NOME_VAR=%5

if %_ANO_BISSEXTO%==1 (set _FLAG_B=b) else (set _FLAG_B=n)

set _N_ACUM_DIAS=0

set _N_MES=1

:: elimina zeros `a esquerda (vi em algum lugar no stackoverflow.com)
SET /a _MES=1%_MES%-(11%_MES%-1%_MES%)/10
:: echo ### _MES=%_MES%
:: -----

:: soma os dias dos meses anteriores, mais a data de hoje
:: por exemplo 1/mai/2019
:: 31 (jan) + 27 (fev) + 31 (mar) + 30 (abr) + 1 (mai) = 120

:LOOP_DIAS_ANO

:: echo === _N_MES=%_N_MES% _MES=%_MES%
if %_N_MES% equ %_MES% goto :FIM_LOOP_DIAS_ANO

set _NOME_MES=mes_%_N_MES%_%_FLAG_B%
call set _DIAS_MES=%%%_NOME_MES%%%
:: echo _NOME_MES=%_NOME_MES% _DIAS_MES=%_DIAS_MES%

set /a _N_ACUM_DIAS+=%_DIAS_MES%
:: echo ano=%_ANO% mes=%_N_MES% dias=%_DIAS_MES% dias_acumulados=%_N_ACUM_DIAS%
set /a _N_MES+=1
goto :LOOP_DIAS_ANO

:: -----

:FIM_LOOP_DIAS_ANO

:: echo dias_acumulados 1: %_N_ACUM_DIAS%

set /a _N_ACUM_DIAS+=%_DIA%
:: echo dias_acumulados 2: %_N_ACUM_DIAS%

set %_NOME_VAR%=%_N_ACUM_DIAS%

goto :EOF

:: -----------------------------------------------------------------------------

It was missing to show the test, but I closed the vm Windows, then put. :)

  • Jeez! Complicated until eh, but the part fácil de quebrar n tendi?

  • batch is very easy to break, any scrambled is risky

  • So as in any language the potential editing results in a possible "break".

  • I am talking about my solution, although generally it is difficult to create complex batch scripts that are robust

  • Yours is mine, there is complexity, in bat, n has to run, n there are ready methods, functions, etc,, to in mobile, then I will see and try to understand.

  • One thing n understood of its edition, because not by the tag cmd?

  • it didn’t have the cmd tag on the original question...now it has, I put...ps. I never do anything on the phone except listen to music and read (and eventually make and receive calls, which is rare)

  • I understand your commentary on the answer as something conflicting, and in practice it is totally unfeasible`. Seen the posted results( images) + the acceptance of the operator. Also 1/2 aggressive, and I do not see as something necessary, but, finally, could explain this point/ theme better? Sorry, I wanted to understand your point of view.

  • 1

    The question is useful in practice, even it can be ported p variations of days, p more and p less. The acceptance accounts for the utility + the vote up received, or ignored these data?

  • days of February: mistake :)

  • @zentrunix With your code I incremented /a /-p /o:n /s /b in the part that " :: filters filenames" in addition to searching in the folders also search in subfolders, sort and bring the path that the file is found to put the script break and behind the entries that would not enter the list , without this increment it works only in the directory where the script is .

  • @Wallsson please create a specific question about this

  • @zentrunix your script searches only in folders, can’t see the files searched in subfolders of folders! It may be because it is currently only " dir /b " but by modifying that part replace the '"/b " by " /s " the broken script

Show 8 more comments

6

I do not know if I understood your question correctly, it would be interesting to put some examples of the filenames and the expected result, but I will try to help in the way I understood and maybe this will guide you a little.

In . bat things are a little limited and I don’t know if it would be possible or not to solve with it, but I believe we probably won’t have problems using Windows Powershell (the "turbine" version of the batch).

Supposing your files follow the following name boss: NOME_ANO_MES_DIA_HHMM.pdf. We can "break" the file name into each of the underlines and store the pieces in an array. In Powershell this is done with Split (documentation). Then we can access each of the pieces and recreate a string only with the date, in a standardized format, so that it is possible to work with them more easily. Powershell has native features to work with dates, similar to C#.

I made a little script to work that way and I believe that’s more or less what you’re looking for. It will list all files (*.pdf) in the directory (the same as where the script is) and then go through each of them, extracting the date information and assembling a string in the month/day/year format and checking whether the difference in days is greater or equal to 5, with reference to the current date of the system. If so, the file name is saved in the log.
It is important to note that if the default file name is different from my example the script will not work and should be suitable, basically modifying the line where the date is extracted($fileDate = $file.Split("_")[2] + "/" + $file.Split("_")[3] + "/" + $file.Split("_")[1]).
Note. The pattern of the time, in this case, is irrelevant.

Example:
Archiv1_2019_04_17_1425.pdf
Archived 2_2019_04_18_0921.pdf
Arquivo3_2019_04_20_0830.pdf
Archive4_2019_04_23_0900.pdf
Archived 5_2019_03_03_0900.pdf
Arquivo6_201903030900.pdf

$actualDate = Get-Date 
$files = ls -n *.pdf
$ErrorActionPreference = "Continue"

Write-Output("**************************") >> log.txt
Write-Output("Inicio do log: $actualDate") >> log.txt
Write-Output("**************************") >> log.txt

foreach ($file in $files) {
    try {
        $fileDate = $file.Split("_")[2] + "/" + $file.Split("_")[3] + "/" + $file.Split("_")[1]
        $fileDate = [datetime]$fileDate
        $diff = $actualDate - $fileDate
        if ($diff.Days -ge 5) {
            $file >> log.txt
        }    
    } Catch {
        Write-Output("Falha ao obter a data do nome do arquivo: $file") >> log.txt    
    }
}

Assuming the current system date is 04/23/2019, the log result would be this:

**************************
Inicio do log: 04/23/2019 12:28:15
**************************
Falha ao obter a data do nome do arquivo: AAlog - Copia.txt
Arquivo1_2019_04_17_1425.txt
Arquivo2_2019_04_18_0921.txt
Arquivo5_2019_03_03_0900.txt
Falha ao obter a data do nome do arquivo: Arquivo6_201903030900.txt

To use Powershell you can use the notepad itself and save the file with the *.ps1 extension and then run it by right-clicking the file and "Run with Powershell". It is also possible to use the Windows Powershell ISE (documentation), which is the native Windows script development environment.

2

The Powershell can fulfill the task much more quickly and simply.

#criando no ambiente uma variável para salvar os nome dos arquivos
$Log = $Env:temp+"\"+(get-date -Format d)+".log"
# caso ocorra uma mais de uma execução, apaga o conteúdo anterior do log
if (Test-Path -Path "$Log") {clear-content -Path "$Log" -Force}
# cria a primeira linha para o log com data no mesmo formato dos arquivos
$Hoje = "Arquivos desatualizados em: "+(get-date -format d)
$Hoje | Out-File -FilePath $Log -append 
# implementando um loop for de 1 a 5 dias para obtenção datas anteriores o mesmo formato dos arquivos
    For ($i=1; $i -le 5; $i++) {
    $File = $(Get-Date).addDays(-$i).ToString("yyyy_MM_dd")
    $List = "*"+$file+"*.pdf"
    # listagem dos possíveis arquivos presentes na pasta escrendo a saída no log
    ls -n "*$file*.pdf" | Out-File -FilePath $Log -Append  
    }
# contagem dos arquivos com datas anteriores encontrados dentro do log 
$Pdf = $(gc $Log -filter ".pdf").count ; "Total de arquivos desatualizado:"+$Pdf | Out-File -FilePath $Log -append 
Out-File -FilePath $Log -append ; Get-Content "$Log"
# listagem do conteúdo do log na tela (stdout)

There is the option to use Alias in the script, getting in the way below:

# Mesmo código em formato compacto fazendo uso de Alias:
#--------------------------------------------------------
$Log=$Env:temp+"\"+(get-date -F d)+".log";if (Test-Path -Path "$Log"){clc -Path "$Log" -Force};$Hoje="Arquivos desatualizados em: "+(get-date -f d);$hoje|Out-File -FilePath $Log -Append
For ($i=1; $i -le 5; $i++) {$File = $(Get-Date).AddDays(-$i).ToString("yyyy_MM_dd");$List = "*"+$File+"*.pdf";ls -n "*$File*.pdf"|Out-File -FilePath $Log -Append};$pdf=$(gc $Log -Filter ".pdf").Count
"Total de arquivos desatualizado: "+$pdf|Out-File -FilePath $Log -Append; Out-File -FilePath $Log -Append;gc "$Log"

# Alias ultilizadas no PS1:
#--------------------------
# -f  |  -Format (Get-Date)
# clc |  Clear-Content
# gc  |  Get-Content  
  • Welcome to the platform ONLY. Allow comment, your solution on Powershell it worked, it’s simpler, the quicker I don’t know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.