03 Oct 2011 @ 9:57 AM 

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
    }
}

Post to Twitter

Posted By: Jeff Wouters
Last Edit: 03 Oct 2011 @ 10:00 AM

EmailPermalink
Tags
Categories: PowerShell, Script, Windows


  • http://twitter.com/JeffHicks Jeffery Hicks

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

  • http://www.jeffwouters.nl Jeff Wouters

    Good idea! Written it down on my todo-list :-)

  • Austin Wimberly

    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?

  • http://www.jeffwouters.nl Jeff Wouters

    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


Get Adobe Flash player
 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 164
  • Comments » 150
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.

Contact



    No Child Pages.