0

I have log files being created in one of my log directory through a powershell. I want to incorporate in the powershell itself a piece of code that will delete the log files from the directory that are logged a couple of days before.

My requirement is my log files should be present only for two days back from current day and rest should be deleted automatically as the powershell runs.

my log files names are as follows which has a time stamp at the end:

abc_log.2013_06_25_17_39_21.log

Could anyone please help me in sorting this out with their valuable piece of code?

1
  • Hi All, The below code worked fine $hours=(Get-Date).Addhours(-24) $abc=get-childitem D:\temp\arun\Log\ -include *.log -recurse |Where {$_.LastWriteTime -le "$hours"}| Remove-Item Commented Jun 27, 2013 at 10:42

2 Answers 2

1

The basic idea is to compare the file's creation date to a specific date time.

$old = (Get-Date).AddDays(-2)

Get-ChildItem $path -Filter *.log | 
Where-Object {!$_.PSIsContainer -and $old -ge $_.CreationTime} | 
Remove-Item
Sign up to request clarification or add additional context in comments.

8 Comments

What do you want to do with the time stamp of your file?
Just thought if we can write a code using the timestamp tail of the log files.That's ok.. When i tried to check the files using the above command as below i am getting the output as below: PS D:\Temp\Arun> Get-ChildItem D:\temp\arun\Log\ -Filter *.log |Where-Object {$_.creationTime -ge ((Get-Date).AddDays(-1))} This is retrieving todays files too.
Get date is getting today date -24 hours so it depends when did you execute it.
I had executed it now itself and my folder has the files since yesterday..But when i execute this command it is retrieving todays date files too.
..Not sure why i am unable to retrieve the records for the previous days using the command :------> Get-ChildItem D:\temp\arun\Log\ -Filter *.log |Where-Object {$_.creationTime -ge ((Get-Date).AddDays(-1))}
|
0

Not powershell tool, but for the practical purposes you may use DELOLDER utility, which can erase files older then specifed age. You may determine file for erasing only some extensions also, and whether it removing with containig old files folder or old files only.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.