PowerShell script to delete files not accessed for more than a week

As Andrew Morgan provided me a good comment in one of my previous posts ( http://jeffwouters.nl/index.php/2011/10/powershell-script-to-delete-files-older-that-a-week/ ), I changed the script a little.
The previous script deleted files created more than 7 days ago, but didn’t care if the files were accessed yesterday or not. This was intended for that specific script and situation, but his command was valid for cases where a company policy slightly differs from the policy in my case.

In my case, all files were to be deleted if they were 7 days or older.
In the new case, all files were to be deleted if they were not accessed for 7 days or longer.

Here’s the new code:

$TargetFolder = “D:\Company\DropBox”
foreach ($i in Get-ChildItem $TargetFolder -recurse)
{
    if ($i.LastWriteTime -lt ($(Get-Date).AddDays(-7)))
    {
        Remove-Item $File.FullName -force
    }
}

And if you only want to include specific extensions, let’s say for example .html and .txt, a little addition to the script is required:

$TargetFolder = “D:\Company\DropBox”
foreach ($i in Get-ChildItem $TargetFolder -recurse -include *.txt, *.html)

    if ($i.LastWriteTime -lt ($(Get-Date).AddDays(-7)))
    {
        Remove-Item $File.FullName -force
    }
}

5 comments

  1. The next step is to turn this into a function where you can specify a path and number of days.

  2. Jeff Wouters says:

    Good idea! Written it down on my todo-list 🙂

  3. Austin Wimberly says:

    austin.wimberly@gmail:disqus.com here:
    So this should be very helpful on a project I am working…..but maybe you guys know of a way to execute this remotely as well?  I have been reading up on psexec commands, but I am not sure I have it down pat.  Any suggestions?

  4. Jeff Wouters says:

    There are multiple ways to accomplish that, but to execute e simple command I would use the following guide: http://www.ravichaganti.com/blog/?p=1108

  5. Al says:

    foreach ($i…

    $File.FullName

    Boom

Leave a Reply

Your email address will not be published. Required fields are marked *