Need help with file deletion script

Dear All
I have created a small script to delete files older than 6 months and i wanted the script record the log for the files it is deleting .

$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
}
else {
write-host "No more files to delete" -ForegroundColor DarkRed
}
}  | out-file $log file 

I get an empty pipe line element is not allowed error when i try to pipe the out put to a $logfile .

Could some one please check this script and let me know what i am doing wrong .
Thanks.

Hi Suresh,

Remove-Item does not return the $File object into the pipeline. Therefore your Out-File after the foreach does not work. You need to pipe the $File object to Out-File within your if statement as suggested in below Gist.

Regards,
Daniel

It is unfortunate. Remove-Item works across multiple PSProviders (files, registry, certificates, etc.). To provide cross-provider familiarity and functionality, some features we think should be there are not, such as the -Passthru switch. And if you look at the help page for Remove-Item you will see there are no outputs.

If you want to do something in the pipeline, checkout Tee-Object. But keep in mind this would have to be upstream to the delete action (here you would be logging intent and not outcome). You might also want to look at result codes and error actions.

Thanks Daniel. It worked Fine
Thakns Bob :slight_smile: