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-Chi...
MicheleSWFWMD
Mar 20, 2023Copper Contributor
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.
CutlerTS
Mar 20, 2023Brass Contributor
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.
& {
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.
- MicheleSWFWMDMar 20, 2023Copper ContributorThank 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.
- LainRobertsonMar 20, 2023Silver Contributor
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