I need Powershell script to delete log files from log folder path older than 180 days, which can be performed using task scheduler.
I wrote this script, but it's not working.
$Path = "C:\Users\akshay.tanpure\Music\logs"
$Daysback = "-180"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse -Include *.log | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item -Force
I've written and use similar on our servers. Editing your code to match the syntax I use successfully ends up with :
$Path = "C:\Users\akshay.tanpure\Music\logs"
$Daysback = -180
$DatetoDelete = (Get-Date).AddDays($Daysback).ToString("MM/dd/yyyy")
Get-ChildItem $Path -Recurse -Include *.log | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item -Force
As Zett42 noted, the -180
doesn't need to be in quotes, and in my case I found I needed to get the date information to the expected date format via ToString("MM/dd/yyyy")