Skip to content

Rename logs at certain size

Most systems have built in the options to automatically switch to a new log file when it reaches a certain size, but some systems do not have that option.

Then it can be handy to be able to do that, i had that need and wrote this script.

You can monitor several log files at the same time, just add or remove $LogArray parameters to match what logs you want to monitor and the set the $LogSize to your preferred size in KB.

The script will rename the files with original name and a timestamp, the script honors the file extension as well.

The time format in the script is Year, Month, Day, Hour, Min and is in 24H format, if you wish to change that the look at row 55 in the script and search the internet for Powershell Get-Date Format to see what options exists.

If our current date and time was 2023-08-21 21:10
example 1:
log1.log would be renamed to log1-202308212110.log
Example 2:
log2.txt would be ranamed to log2-202308212110.txt

Important to note is that it will rename the existing file and the system creating the log files must be able to create a new one when ever it need to write data to it.

The script in it's full glory.

# Rename a specified log file when it reaches a certain size.

# Create empty Array for log files
$LogArray = @()

# Log Files to monitor.
$LogArray += "C:\Temp\Log1.log"
$LogArray += "C:\Temp\Log2.txt"

# Size to adhere to in KB
$LogSize = 10240

# Do the check
foreach($f in $LogArray){
    # Run only if file exists.
    if((Test-Path $f)){
        # Get file information.
        $fName = (Get-Item $f).BaseName
        $fExt = (Get-Item $f).Extension
        $fPath = (Get-Item $f).Directory

        # Get size in KB
        $fSize = [string]::Format("{0:0}", (Get-Item $f).length / 1KB) -as [int]

        # If size of file is bigger than $LogSize rename it.
        if($fSize -ge $LogSize){
            # Add date and time to file when renamed.
            $fStamp = Get-Date -Format "yyyymmddhhmm"

            # Rename the file.
            Rename-Item -Path "$fPath\$fName$fExt" -NewName "$fName-$fStamp$fExt"

            # Write files that are renamed.
            Write-Host("Renamed: $fName$fExt => $fName-$fStamp$fExt")

            ## Test Only
            #Write-Host("Yes, $fPath, $fName, $fExt")
        else {
            # Write files that are unchanged.
            Write-Host("Unchanged: $fName$fExt")
        # Write files that do not exist.
        Write-Host("Missing: $fName$fExt")