Author Posts

June 22, 2016 at 8:38 pm

I'm new to PowerShell and need to know how would I delete all archived log files (c:\WINDOWS\system32\logfiles\) older than 365 days on Windows Server 2008 R2?
I have figured out, with Don's help, how to do this using the following script: Get-Childitem *logfile | where-object { $_.LastAccessTime -lt ((Get-Date).AddDays(-365)) } | Remove-Item
But now I need to create a logfile with a date/time stamp to show all the files over 365 days that were deleted?
Would I export to a CSV file in the same directory?
Any suggestions, assistance, or advice would be appreciated?
Thanks,
Bob

June 22, 2016 at 9:23 pm

You might do something like this:

Get-Childitem *logfile |
where-object { $_.LastAccessTime -lt ((Get-Date).AddDays(-365)) } | 
ForEach-Object {
    $_ | Remove-Item
    $_ | Select-Object -Property LastWriteTime, LastAccessTime, FullName
} |
Export-Csv -Path "C:\Path\To\DeletedLogs_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv" -NoTypeInformation -UseCulture