Powershell – Dynamically Tail Log File

I originally made this script to tail a certain program’s log files.  The program started logging, then when the file size hit 1024kb, it created a new file, keeping 10 files total in the directory.  This was tough to track any issues over time as the log files were constantly getting renamed, then destroyed as new log entries came into play.  This Powershell script takes the root log file and continuously tails it to a new file.  It also outputs some stats re. total lines and elapsed time.

				
					# This script tails a log file, then copies each line to a separate file.  It will also timestamp the file, then write-host every 1000 lines with a timestamp

# Define the input and output file paths
$inputFilePath = "C:\path\to\input.log"
$outputFolderPath = "C:\path\to\output"
$outputFileName = "{0}_DynamicTail.log" -f (Get-Date -Format "yyyy-MM-dd_HHmm")

# Combine the output folder path and file name to create the full output file path
$outputFilePath = Join-Path $outputFolderPath $outputFileName

# Get the start time
$startTime = Get-Date

# Write the start time to the console
Write-Host "Script started on $($startTime.ToString())"

# Initialize a line count variable
$lineCount = 0

# Start tailing the input file
Get-Content $inputFilePath -Tail 0 -Wait | ForEach-Object {
    # Append each line to the output file
    Add-Content $outputFilePath $_
    # Increment the line count
    $lineCount++
    # Write the current line count to the console every 1000 lines
    if ($lineCount % 1000 -eq 0) {
        Write-Host "Lines written: $lineCount"
    }
    # Calculate the elapsed time
    $elapsedTime = New-TimeSpan $startTime (Get-Date)
    # Write the elapsed time to the console every 1000 lines
    if ($lineCount % 1000 -eq 0) {
        Write-Host "Elapsed time: $($elapsedTime.ToString())"
    }
}