How to get output to file from Remove-Item

Copper Contributor

Very new to Powershell. I have a script that goes through a folder and removes files not accessed within 14 days. I have been unable to get the output of removed files to write to a file.

 

Get-Childitem D:\Users -Recurse  |

where-object {$_.lastAccessTime -lt (get-date).adddays(-14)} |

foreach{remove-item $_.fullname -recurse -force -verbose -whatif}

 

I've tried redirection, Output-File, etc. I may just be placing it in the wrong spot.

Thanks

5 Replies
I'm not an expert in PowerShell, but I don't see write-host (or any output statements/flags) within the foreach statement.
Thank you, yes, I have tried Output-File within the brackets as well as redirection "*>" and out side the brackets after the foreach. I posted the working script which outputs to the console, Just need to find how to add the file to log to.
I Googled up a solution. It appears that it can't output within the loop. Rather, it suggest piping the whole thing, like maybe this way:

& {
foreach {remove-item $_.fullname -recurse -force -verbose -whatif}
} | Out-File MyLog.txt -Append

You can just Google "powershell foreach log to file" to find different solutions that best fits your need.
Thank you, I will try that. I have been down the Google trail and wasn't able to get any to work. I will continue to test.

@MicheleSWFWMD 

 

You're both on the right track.

 

Here's a basic version that will do what's requested. It's not the most efficient version but it is more readable than one that is.

 

$LogFile = ".\SomeLogFile.log";
Remove-Item -Path $LogFile -Force -ErrorAction:SilentlyContinue;

Get-Childitem D:\Users -Recurse |
    ForEach-Object {
        if ($_.LastAccessTime -lt (Get-Date).AddDays(-14))
        {
            $_.FullName | Out-File -FilePath $LogFile -Append;
            $_ | Remove-Item -Recurse -Force;
        }
    }

 

Cheers,

Lain