PowerShell Logging Part 2 — Rotating Your Logs

 

A few weeks ago, I wrote a post about using PowerShell for logging script outputs and mentioned there’d be a part two. So here we go, finally.

PowerShell logging is great for keeping track of data, but log files can quickly get too big. This makes it hard to find what you need or manage storage. With a simple script, you can split logs into separate files when needed.


$logPath = "c:\Scripts\NICPingCheck.log"

#Check if old log files exist and delete them
if (Test-Path "$logPath.old") {
    Remove-Item "$logPath.old" -Force
    Write-Host "Old log file removed."
} else {
    Write-Host "No old log file found to remove."
}

#Rename the current log file to .old
if (Test-Path $logPath) {
    Rename-Item -Path $logPath -NewName "$logPath.old" -Force
    Write-Host "Current log file renamed to .old."
}

The script starts by deleting any files ending in .old. Next, it renames the current log file to add .old, so you always have at least one backup to review. You can also tweak it by using StampMe or adding extra details to the file name.

This simple script keeps your log files from getting out of control, and you can easily build on it to add more features.

Links

Comments

Popular posts from this blog

Home Lab Hardware 2.0 – New Hosts

PowerShell Logging — Recording the Output of Your Scripts