Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$Targetfolder ="C:\temp\logs"
$Extension = "*.log"
$logfile = New-Item -Path 'C:\TEMP' -ItemType "file" -Name deleted.log
$files = Get-ChildItem $Targetfolder -Include $Extension -Recurse | where {$_.LastWriteTime -lt (get-date).Adddays(-180)}
foreach ($File in $Files)
{
if ($File -ne $Null)
{
write-host "Deleting File $File" -BackgroundColor DarkGreen
Remove-item $File.Fullname -Force
# Remove-Item does not return the $File object back to the pipeline.
# You need to include the Out-File within the foreach loop where you have access to the $File object.
$File.FullName | Out-File -FilePath $logfile -Append
}
else {
write-host "No more files to delete" -ForegroundColor DarkRed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment