2

This is the command i am running which deletes all files in directory

set folder="C:\dashboard\DATA"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)

How do i only delete the files that were last modified more than 5 minutes ago

Compo
  • 36,585
  • 5
  • 27
  • 39

2 Answers2

1

In PowerShell it would be:

Get-ChildItem | Where-Object LastWriteTime -lt ([DateTime]::Now).AddMinutes(-5) | Remove-Item

Or, using usually known aliases:

ls | where LastWriteTime -lt ([DateTime]::Now).AddMinutes(-5) | rm

To use this in bat or cmd you can invoke PowerShell explicitly:

powershell -NoProfile -Command "ls c:\path | where LastWriteTime -lt ([DateTime]::Now).AddMinutes(-5) | rm"
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
  • what about Cmd? – maher blockchain Oct 11 '22 at 10:20
  • I expect plain cmd to be a mess. See https://stackoverflow.com/questions/27296934/file-is-older-than-4-minutes-in-batch-file – Paweł Dyl Oct 11 '22 at 10:46
  • With a batch file you can write some thing like that : `@echo off & powershell -NoProfile -ExecutionPolicy Bypass -Command "ls C:\dashboard\DATA | where LastWriteTime -lt ([DateTime]::Now).AddMinutes(-5) | rm -WhatIf" & pause` – Hackoo Oct 11 '22 at 10:54
  • 3
    You do not need to use or waste realestate with `-ExecutionPolicy` when using `-Command`s. An execution policy is required only when running PowerShell scripts, _(i.e. `-File`s)_. – Compo Oct 11 '22 at 11:56
0

With a batch file you can write something like that :


@echo off
Powershell -C "ls C:\dashboard\DATA | where LastWriteTime -lt ([DateTime]::Now).AddMinutes(-5) | rm -WhatIf"
pause

If everything is OK , just remove -WhatIf

Hackoo
  • 18,337
  • 3
  • 40
  • 70