Assistance with Creating Logfile of Files Deleted

I am new at Powershell. I am trying to delete files older than 30 days which I can do. I need help to log all of the files that were deleted to a file.
Here is what I have. It works except the logfile is blank:

$Daysback = "-30"
$NewPath = "C:\Temp\test_folder" 
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)

Get-ChildItem $NewPath -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } |Remove-Item -Verbose | Out-File "c:\temp\log\DeletedFiles_Log.txt" -Append

If you break the script up a bit you can get much more details and export to a csv. This would log what was successful, failed (why it failed), and the deletion date. The file properties you want can be logged, such as BaseName, Length, etc. to get additional details from the files being processed (if required). Here is an example:

$NewPath = "C:\Scripts" 
$DatetoDelete = (Get-Date).AddDays(-30)

$files = Get-ChildItem $NewPath -Recurse -File | 
            Where-Object { $_.LastWriteTime -lt $DatetoDelete } 

$results = foreach ($file in $files) {
    try {
        $file | 
            Remove-Item -WhatIf -ErrorAction 'Stop'

        $file |
            Select FullName,
                   @{Name='DateDeleted';Expression={Get-Date}},
                   @{Name='Status';Expression={'success'}}
    }
    catch {
        $err = $_

        $file |
            Select FullName,
                @{Name='DateDeleted';Expression={$null}},
                @{Name='Status';Expression={'failed {0}' -f $err}}
    }
}
        
 $results |
    Export-Csv -Path "c:\scripts\DeletedFiles_Log.csv"
```
1 Like

This is exactly what I was looking for. I had never seen the -whatif parameter used before so I am going to look into this some more. Thank you for the help, @rob-simmers