Search code examples
powershelllogrotate

RotateLog with powershell


I am new to scripting and Powershell, and I am trying to create a script to keep every day the log files of the 3 last days only

function RotateLog {
$dir="C:\Users\user1\Documents\Project\LOG"
$DayMax= -3
$CurrentDate= Get-Date -uformat "%d-%m-%Y-%H%M"
$DatetoDelete= (get-date -UFormat "%d-%m-%Y-%H%M").AddDays($DayMax)

get-childitem -path $dir -filter "YYYY-mm-dd-*.LOG"
foreach-object {
if ($_.LastWriteTime -lt $DatetoDelete)
{remove-item}
}
}

When I run $DatetoDelete it returns failed because [System.String] does not contain a method named 'AddDays'.

So I tried to replace the variable by

$dtt=(get-date).AddDays($DayMax)

It is working this way, but I need to get the format . How can I do it ?

Another problem, when I run the command remove-item, it returns cmdlet remove-item at command pipeline position 1 Supply values for the following parameters:path[0] What does it mean ?


Solution

  • The -Format and -UFormat parameters make Get-Date output a string representation of the corresponding [datetime] object, and "adding -3 days to a string" doesn't make much sense.

    Use Get-Date without a format parameter to get a [datetime] object that can be meaningfully modified and compared instead:

    # Get current date and time as a [datetime] object
    $CurrentDate = Get-Date
    
    # Here I reference the `Date` property on our DateTime object
    # this gives us the same date, but at 00:00 local time
    $DateToDelete = $CurrentDate.Date.AddDays($DayMax)
    

    Now, $_.LastWriteTime -lt $DatetoDelete makes a lot more sense, as we're comparing [datetime] to [datetime] rather than to a formatted string