How To Find And Remove Old Files In PowerShell


So I have all these files in my backup folder. How can I keep only the files modified at most seven days ago, whilst removing the rest?

Short Answer

We can use a simple chain like this:

Get-ChildItem -Recurse |

    # change the extension as appropriate
    ?{ $_.Extension -eq ".bak" } |

    # change the time window as appropriate
    ?{ $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |

    # now remove the results

We can then add or remove filters to this pattern as appropriate to your scenario.

So what more stuff can we add?

Continue reading “How To Find And Remove Old Files In PowerShell”