Mar 20 2023 10:08 AM
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
Mar 20 2023 10:18 AM
Mar 20 2023 10:32 AM
Mar 20 2023 10:59 AM
Mar 20 2023 11:01 AM
Mar 20 2023 04:28 PM
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