Forum Discussion
MicheleSWFWMD
Mar 20, 2023Copper Contributor
How to get output to file from Remove-Item
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
- CutlerTSBrass ContributorI'm not an expert in PowerShell, but I don't see write-host (or any output statements/flags) within the foreach statement.
- MicheleSWFWMDCopper ContributorThank 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.
- CutlerTSBrass ContributorI 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.