PowerShell Script: Delete Files Older Than 7 Days

PowerShell Script: Delete Files Older Than 7 Days

Another file operations PowerShell script that was recently required. This time we had a folder that contains a large number of log files that were never rotated and took up a large amount of disk space. These logs are only used for troubleshooting issues if they occur and it is rarely required for us to go over log files older than 7 days, so why are we keeping the rest?

Here is an easy one liner to help!

Until next time!

Get-ChildItem –Path “E:\TEMP\Logs” –Recurse | Where-Object{$_.LastWriteTime –lt (Get-Date).AddDays(-7)} | Remove-Item
PowerShell Script: Move and Rename Log Files

PowerShell Script: Move and Rename Log Files

Recently, I had a requirement to move log files out of a folder before the next 24 hour period began. The reason for this was because the log files were being amended to each day. This was generating some very big log files and making it difficult to determine events that occurred on a particular day as each file name only contained a timestamp.

So I quickly wrote up a PowerShell script to grab the files modified in the last 12 hours and move them to a separate folder and then renaming them to include today’s date as a prefix in the file name. I then have a scheduled task set to run the script every 12 hours. It is a very simple script but I have set some variables at the top so anyone can easily reuse the script if they need it.

Until next time!

## Set time frame
$date = (Get-Date).AddHours(-12)
## Get Today's Date
$today = Get-Date -Format yyyyMMdd
## Set Source Folder
$source = "E:\Log\"
## Set Destination Folder
$destination = "E:\LogArchive\"

## Get list of files to Move
$files = Get-ChildItem $source | Where-Object {$_.LastWriteTime -lt $date}

## Move and Rename the files
foreach ($file in $files){
 Move-Item $source$file $destination
 Rename-Item $destination$file $destination$today$file
}