Share via


Script to delete files and folders older than X days

Question

Thursday, May 3, 2018 3:51 PM

I wish to run a script daily that will delete folders and respective files in it which are older than X days (for my webcam recordings). I have the following script, though when run, files are not deleted.

# Enter a number to indicate how many days old the identified file needs to be (must have a "-" in front of it).
$HowOld = -1

#Path to the root folder
$Path = "E:\CAMMEDIA"

#Deletion task
get-childitem $Path -recurse | where {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -whatif}

Powershell screenshot:

I also created a Task Scheduler Task; the following is in the argument section:

<pre>-ExecutionPolicy Bypass c:\scripts\myscript.ps1 -RunType $true -Path E:\CAMMEDIA</pre>

Suggestions?

All replies (2)

Thursday, May 3, 2018 4:20 PM

Have you tried it without the -whatif?


Thursday, May 3, 2018 4:30 PM

I needed to replace whatif with verbose. Here's what I ended up with...

#Days older than
$HowOld = -1

#Path to the root folder
$Path = "E:\CAMMEDIA"

#Deletion files task
get-childitem $Path -recurse | where {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -verbose}

#Deletion empty folders task
do {
  $dirs = gci $Path -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ }
} while ($dirs.count -gt 0)