Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script to logrotate logs

Tags:

powershell

Ok.So I want to write a PowerShell script that simulates(sort of) the LogRotate option found in Linux.For one single file:no problem.But I want it to work for all the file INSIDE a folder.But...It doesn't work...at all.I tried doing it with foreach-object but it still doesn't work.I'm new to PowerShell programming,so you'll have to excuse me if my script doesn't look so clean. Here it is:

function RotateLog {
    $log = "C:\Users\nvali\Desktop\scripts"
    Push-Location $log
    $target = Get-ChildItem $log -Filter "*.txt"
    $threshold = 300
    $datetime = Get-Date -uformat "%Y-%m-%d-%H%M"
    #$target_path =Get-ChildItem $log
    $filesize = $target.length/1MB
    $target | ForEach-Object {
        if ($filesize -ge $threshold) { 
            $filename = $_.name -replace $_.extension,"" 
            $newname = "${filename}_${datetime}.log_old"
            Rename-Item $_.fullname $newname
            $rotationmessage = ""
            Write-Host "Done" 
        }
        echo "$rotationmessage"
    }
}
like image 760
CoreBlazer Avatar asked Nov 07 '22 22:11

CoreBlazer


1 Answers

You needed to check the file size of each file inside your foreach as LotPings mentioned, and as BenH commented, inside the foreach you need to use $_ to access the current object that is being accessed.

This script worked for me without any errors.

function RotateLog {
$log = "C:\logDir"
$target = Get-ChildItem $log -Filter "*.txt"
$threshold = 30
$datetime = Get-Date -uformat "%Y-%m-%d-%H%M"
$target | ForEach-Object {
    if ($_.Length -ge $threshold) { 
        Write-Host "file named $($_.name) is bigger than $threshold KB"
        $newname = "$($_.BaseName)_${datetime}.log_old"
        Rename-Item $_.fullname $newname
        Write-Host "Done rotating file" 
    }
    else{
         Write-Host "file named $($_.name) is not bigger than $threshold KB"
    }
    Write-Host " "
}
like image 159
Brandon McClure Avatar answered Nov 14 '22 23:11

Brandon McClure