Powershell script for logs logrotat

Ok.So I want to write a PowerShell script that mimics (sorts) the LogRotate parameter found on Linux. For a single file: no problem. But I want it to work for the entire INSIDE file in the folder. But ... It doesn't work ... at all. I tried to do it with a 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 he 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"
    }
}

      

+3


source to share


1 answer


You needed to check the file size of each file inside your foreach as LotPings , and like BenH , inside foreach you need to use $_

to access the current object being accessed.

This script worked for me without error.



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 " "
}

      

0


source







All Articles