0

I want to browse through the folder3 and delete child files and folders, if their CreationTime and LastWriteTime are older than 1 month:

ls -r -force 'd:\folder1\folder2\folder3' |
    where {($_.fullname -like 'd:\folder1\folder2\folder3\*') -and ($_.creationtime -le (get-date).addmonths(-1)) -and ($_.lastwritetime -le (get-date).addmonths(-1))} |
    sort -desc fullname |
    rm -force

How do I answer "No" to all the confirmations it asks when the folder is not empty? I only need folder deletion if it's empty.

-Confirm:$False or -ErrorAction SilentlyContinue statements do not help.

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
dvb15
  • 1
  • 1
  • I would do a two pass on this, firstly delete only files that meet your criteria, then a second pass to delete empty folders. Quick search brings me to this answer, you'll need to update with your criteria: https://stackoverflow.com/a/19326146/2208505 – henrycarteruk Mar 28 '19 at 09:35

1 Answers1

0

Try something like this:

Get-ChildItem –Path "d:\folder1\folder2\folder3" -Recurse | 
    Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30)) -and 
                  ($_.CreationTime -lt (Get-Date).AddDays(-30))} | 
    Remove-Item -Force
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
  • How's this solve my problem? It will ask for deletion in case of a non-empty folder (if there're files newer, than 30 days). Besides, you changed my conditions to deletion. I need to analyze both dates: creation and lastchange – dvb15 Mar 28 '19 at 08:55
  • You can add `((gci $_.fullName -Force).count -eq 0)` in the condition for picking the nonempty. My bad I missed the creation part. Edited it – Ranadip Dutta Mar 28 '19 at 09:07
  • Yes, finally I made something like this (using if-then-else). Pity, that powershell doesn't have such a parameter... Thanks! – dvb15 Mar 28 '19 at 10:01