Reputation: 878
I am lookng for creating a batch file for below requirement:
Root Folder - D:\Olderfiles\SourceDocuments
Inside this root folder we have many folders and sub folders. In each of these folders we may or may not have folder called Archive. We need to delete *.xlsx files not updated in last 120 Days from these folders named as “Archive”.
I tried below script, but it is not working as expected.
forfiles /p "D:\Olderfiles\SourceDocuments" /s /m *\Archive\*.xlsx /D -120 /C "cmd /c del @path"
Any help will be greatly appreciated.
Upvotes: 0
Views: 724
Reputation: 16236
In your batch script, you can use a PowerShell script. This uses some features of the current PowerShell 5. It can be done with older versions with some changes. When you are confident that the correct files will be deleted, remove the -WhatIf
from the `Remove-Item cmdlet.
=== delold.ps1
Get-ChildItem -Recurse -Directory -Path 'D:\Olderfiles\SourceDocuments' -Filter 'Archive' |
ForEach-Object {
Get-ChildItem -File -Path $_.FullName -Filter '*.xlsx' |
ForEach-Object {
if ($_.LastWriteTime -lt (Get-Date).AddDays(-120)) {
Remove-Item -Path $_.FullName -WhatIf
}
}
}
=== delold.bat
powershell -NoLogo -NoProfile -File "delold.ps1"
Upvotes: 1
Reputation: 3264
There are known bugs in ForFiles Date Checking in certain versions of Windows.
To get around this you can use Robocopy to generate the list of matching Files, and then delete them using a For Loop:
MD "%temp%\Empty"
FOR /F "Tokens=*" %%A IN ('
ROBOCOPY "D:\Olderfiles\SourceDocuments" "%temp%\Empty" *
/MinAGE:120
/L /NP /NC /NS /FP /NDL /NJH /NJS
^| FINDStr /I /R /C:"\\Archive\\.*\.xlsx$"
') DO @(
DEL /F/Q "%%~A"
)
Depending on the number of files and subdirectories this or ForFiles could still take quite a while as you only care about "Archive" folders.
So, to speed this up, lets only check the directories that are named "ARCHIVE" using DIR to match just those, and then we loop that list to run the robocopy:
This is going to be much faster then Forfiles or the above loop:
MD "%temp%\Empty"
FOR /F "Tokens=*" %%a IN ('
DIR /AD/S/B "D:\Olderfiles\SourceDocuments\*Archive"
') DO (
FOR /F "Tokens=*" %%A IN ('
ROBOCOPY "%%~A" "%temp%\Empty" *
/MinAGE:120
/L /NP /NC /NS /FP /NDL /NJH /NJS
^| FINDStr /I /R /C:"\\Archive\\.*\.xlsx$"
') DO (
DEL /F/Q "%%~A"
)
)
If you are just pasting this into the CMD line then you need to use this which just removed a % sign from each loop variable:
MD "%temp%\Empty"
FOR /F "Tokens=*" %a IN ('
DIR /AD/S/B "D:\Olderfiles\SourceDocuments\*Archive"
') DO (
FOR /F "Tokens=*" %A IN ('
ROBOCOPY "%~A" "%temp%\Empty" *
/MinAGE:120
/L /NP /NC /NS /FP /NDL /NJH /NJS
^| FINDStr /I /R /C:"\\Archive\\.*\.xlsx$"
') DO (
DEL /F/Q "%~A"
)
)
Upvotes: 1