Tuesday, May 31, 2011

PowerShell Log Rotation Function

Here is a handy PowerShell function for rotating logs.

# Function to Check Log Size and Rotate as Needed
    function RotateLog($log) {
        $threshold = 100 # Size of File in Megabytes when Log Should Be Rotated
        $file = Get-Item "$log" # Get Log File
        $filedir = $file.directory.fullname # Get Log Directory
        $server = HostName
        $filesize = $file.length/1MB # Get Current Size of File
        $datetime = Get-Date -uformat "%Y%m%d-%H%M" # Get Current Date and Time
        $fdatetime = Get-Date -uformat "%B %e, %Y - %H%M hours" # Get Formatted Current Date and Time
        $arcdir = "$filedir\archive" # Specify Log Archive Directory
        if ((Test-Path -Path $arcdir -PathType container) -ne $True) # Verify that the Archive Directory Exists - If not, Create it
        {
            New-Item $arcdir -Type directory # Create Directory if it does not Exist
        }
        if ($filesize -gt $threshold) { # Compare Log File Size to Specified Threshold
            $filename = $file.name -replace $file.extension,"" # Remove File Extension from Name
            $newname = "${filename}_${datetime}.log" # Specify New Name for Archived Log
            Rename-Item -Path $file.fullname -NewName $newname # Rotate Current Log to Archive
            Move-Item $newname -Dest "$arcdir" # Move Archived Log to Archive Directory
            $rotationmessage = "-----------------------------------------------------------
Log rotation occured - $fdatetime
Rotated log available here: ${arcdir}\${newname} on $server
-----------------------------------------------------------
" # Log Rotation Message
            Write-Host "$rotationmessage" # Echo Log Rotation Message to Console if Active
            echo "$rotationmessage" | Out-File -FilePath "$log" -Append # Create New Log and Record Log Rotation in New Log
        }
    }
    
# Call Function
$log = "C:\myprogram\logs\main.log" # Specify Log File
RotateLog($log) # Call Log Rotation Function

No comments:

Post a Comment