Home > Net >  Need a cmd/powershell script to delete files for than 30 days old in nested folders
Need a cmd/powershell script to delete files for than 30 days old in nested folders

Time:01-17

We have 30 processes running which generate error screenshots. So we only keep 30 days worth I've been trying to write a Powershell script to do this. The problem I'm facing is with wildcards in the folder crawl. Say I have the following files:

C:\Runs\Process-1\AppFiles\Dummy.txt
C:\Runs\Process-1\AppFiles\Dummy.png
C:\Runs\Process-2\AppFiles\DummyPic.png
C:\Runs\Process-3\AppFiles\Dummy.log
C:\Runs\Process-3\AppFiles\Dummy1.png

And I want to get rid of all the png files in those subfolders more than 30 days old.

I tried:

    ForFiles /p "C:\Runs\Process*" /s /d -30 /m "*.png"

but it doesn't like my folder wildcard. Help anyone?

CodePudding user response:

In Powershell you may try this:

Get-ChildItem "C:\Runs\Process*\AppFiles\*.png" | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-30) } | Remove-Item

CodePudding user response:

I would suggest using nested forfiles loops:

  • An outer forfiles loop for the directories, Process-*, and;
  • An inner forfiles loop for the *.png files that you wish to delete.

This way you have the additional flexibility of two loops to play with.


Another less elegant method would be to use a foreach-object loop, again containing a nested ForFiles, with a list of directories supplied to the foreach-object. However, then you have to use a pre-determined list of directories. Obviously, you could also use foreach-object for the inner loop as well, but again you would need a pre-determined list of .png files, which pretty much defeats the whole object of the exercise.

The nested forfiles approach is much better, IMHO.

  • Related