Groups > Microsoft > Windows PowerShell > Re: How to delete "old" directories (recursively)?




How to delete "old" directories (recursively)?

How to delete "old" directories (recursively)?
Mon, 14 Apr 2008 15:28:58 -050
Hello,

I have a very deeply nested directory structure which is part of a
loadbuild system. Because our loadbuild machine periodically runs out of
space, I would like to run a scheduled task which deletes old
build artifacts.

So, how can I make a powershell script which deletes (recursively)
directories which are older than X days? I'm not that familiar with the
.NET APIs, which is (I think) why I'm running into trouble on this one.

Post Reply
Re: How to delete "old" directories (recursively)?
Mon, 14 Apr 2008 20:30:49 -070
Get-ChildItem -Recurse -Path .\* |
where{ ($_.mode -match '^d.*') -and
(([datetime]::Today-$_.CreationTime.Date).Days -gt X) } |
%{ Remove-Item $_ }


It's all one line.
Post Reply
Re: How to delete "old" directories (recursively)?
Mon, 14 Apr 2008 21:31:07 -030
David Stuart wrote:
> Hello,
> 
> I have a very deeply nested directory structure which is part of a
> loadbuild system. Because our loadbuild machine periodically runs out of
> space, I would like to run a scheduled task which deletes old
> build artifacts.
> 
> So, how can I make a powershell script which deletes (recursively)
> directories which are older than X days? I'm not that familiar with the
> .NET APIs, which is (I think) why I'm running into trouble on this one.
> 
> Thanks for the help. I imagine this is pretty easy for powershell
veterans.

Here's how I list all directories older than 2008 starting in c:\program 
files:
PS C:\Program Files> get-childitem . -rec| ` 
where-object{$_.psiscontainer -and ($_.lastwritetime -lt
"01/01/2008")}

Now to actually delete (just add this to the above command):
|foreach-object{remove-item $_ -recurse -whatif}

-whatif so you can check out what would be deleted.  You can do a 
start-transcript, run the above with the -whatif, stop-transcript, then 
review the log of what should be deleted to make sure if meets your 
requirements.

Marco

-- 
Microsoft MVP - Windows PowerShell
http://www.microsoft.com/mvp

PowerGadgets MVP
http://www.powergadgets.com/mvp

Blog:
Post Reply
Re: How to delete "old" directories (recursively)?
Tue, 15 Apr 2008 16:57:32 -050
On Mon, 14 Apr 2008 20:30:49 -0700, ajax76 wrote:

> Get-ChildItem -Recurse -Path .\* |
> where{ ($_.mode -match '^d.*') -and
> (([datetime]::Today-$_.CreationTime.Date).Days -gt X) } |
> %{ Remove-Item $_ }
> 
> 
> It's all one line.
> Replace X for real value of days and .\* for real path.

Thanks ..

Post Reply
about | contact