Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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" } } |
Answer:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 " " } |