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}
Your script has a -WhatIf, which will not delete the files, only report what will be done. If you remove the -WhatIf, does the script work manually? If the script works manually, then the next question is what user is running the script in the scheduled task?
# Enter a number to indicate how many days old the identified file needs to be
$HowOld = '1'
#Path to the root folder
$Path = "E:\CAMMEDIA"
#Deletion task
get-childitem $Path -recurse -file | where { (get-date) - $_.lastwritetime -gt $HowOld } |
remove-item -force -verbose
Remove -WhatIf will delete the files, performing the operation. If you are looking for logging, you can do use the -Verbose switch or just add $filesToDelete to the script to enumerate or something like: