header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

Do Not Remove Directories
Last Post 25 Aug 2008 05:23 PM by Ayth. 4 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
AythUser is Offline
New Member
New Member
Posts:15

--
25 Aug 2008 05:06 PM  

Hello,

Been a long time since I've graced this amazing forum with a question, so I thought I would....or actually I'm forced to becuase I'm not sure how to proceed. I know this is a simple answer, but I'm not sure.

My situation is as follows. I need a script to delete files older than x days in a specified path. I took a look at Ying Li's script on myitforum.com, link is here:

http://myitforum.com/cs2/blogs/yli628/archive/2007/10/02/powershell-script-to-delete-files-older-than-certain-days.aspx

I have modified it for my use and it is as follows:

Function GetOldFile
{
 param($Dir = $args[0],
        $Days = $args[1]
)
#echo $strComputer $Dir $Days

 if (Test-Path $Dir)
 {

  $Now = Get-Date

 # Notice the minus sign before $days
  $CreateTime = $Now.AddDays(-$days)
# Get all of the items within our path, whose lastwrite time is
Get-ChildItem $Dir -recurse |Where {$_.CreationTime -le "$CreateTime"}|Remove-Item -recurse -force -whatif| out-file v:\TestFolders\CleanLog.txt -append
 }
}
GetOldFile

 

As you can see it takes two arguments a path and a numeric integer which corresponds to the date I want to keep. However, I need to keep the folders and delete the files. The folder structure is required to be kept. Can anyone give me a start on what to look at? Thanks.

 

Cheers,

Ayth

 

ShayUser is Offline
Basic Member
Basic Member
Posts:228

--
25 Aug 2008 05:10 PM  
Change the where clause to:

Where {!$_.PSIsContainer -and ($_.CreationTime -le "$CreateTime") }
AythUser is Offline
New Member
New Member
Posts:15

--
25 Aug 2008 05:14 PM  
Thanks, will give it a try. Someone mind explaining the "!" within the where clause? I haven't ran into it before.

Cheers.
ShayUser is Offline
Basic Member
Basic Member
Posts:228

--
25 Aug 2008 05:20 PM  
It is the negating sign, you can use -not if you prefer (they are the same):

Where { -not $_.PSIsContainer -and ($_.CreationTime -le "$CreateTime") }

If $_.PSIsContainer is $true the the current object is a directory. Basically !$_.PSIsContainer is like saying 'if its not a directory'.
AythUser is Offline
New Member
New Member
Posts:15

--
25 Aug 2008 05:23 PM  
Sweet! That is one to remember, and it works. Saw it using the -whatif parameter. Will now remove the -whatif. Thanks Shay.
You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer