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
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s