1

I would like the powershell script to generate new log file with the same name and copy old log file to new file with new name if that log file will exceed certain size, like for example log.1 file extension.

I implemented basic Add-Content command with file directory as a variable:

$logmsg = $date + " " + $status.ToString() + " " + $item + " " + $perf + " " + $output

Add-Content D:\...\..._log.txt -Value $logmsg

I don't actually need to script to create more log files like for example log.2, log.3 and etc. I just need to keep old logs in this log.1 file and if the size of original log file will exceed again, log.1 file can be overwritten.

Couldn't find any method for PS scripting specifically.

lubierzca
  • 160
  • 2
  • 14

1 Answers1

1

If I understand your question correctly, you would like to keep one current log file and if it exceeds a certain size, the content should be stored away in another file and the current log file should then be emptied.

You can do this like so:

$logfile    = 'D:\...\..._log.txt'   # this is your current log file
$oldLogs    = 'D:\...\old_logs.txt'  # the 'overflow' file where old log contents is written to
$maxLogSize = 1MB                    # the maximum size in bytes you want

$logmsg  = $date + " " + $status.ToString() + " " + $item + " " + $perf + " " + $output

# check if the log file exists
if (Test-Path -Path $logfile -PathType Leaf) {
    # check if the logfile is at its maximum size
    if ((Get-Item -Path $logfile).Length -ge $maxLogSize) {
        # append the contents of the log file to another file 'old_logs.txt'
        Add-Content -Path $oldLogs -Value (Get-Content -Path $logfile)
        # clear the content of the current log file 
        # or delete it completely with Remove-Item -Path $logfile -Force
        Clear-Content -Path $logfile
    }
}

# keep adding info to the current log file
Add-Content -Path $logfile -Value $logmsg

Hope this helps

Theo
  • 57,719
  • 8
  • 24
  • 41