Reputation: 13
i have probably searched the whole web, but I'm not able to help myself. Otherwise I'm just incapable. All I want is to delete folders after 30 days and display the results in a simple .log file.
dir "C:\Users\sam\Desktop\Files_todelete\*" -ErrorAction SilentlyContinue | Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } | Remove-Item -Recurse
This works for me, but I tried nearly everything to log the results. Hopefully you can help me to fix this issue.
Upvotes: 0
Views: 274
Reputation: 13
So in this case it worked for me, but I want to use the Script for network drives. If I edit the path everything seems to be fine. But the problem here is the permission. Therefore I found a solution with Get-ChildItem -Directory. My question here is can pipe this in front of the Remove-Item command?
Like:
$LogFile = '\netshare\folder\log.txt'
dir "\netshare\Files_todelete*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } |
ForEach-Object {
Get-ChildItem -Directory | Remove-Item $_.FullName -Recurse
Out-File -InputObject $('Removed {0}' -f $_.FullName) -FilePath $LogFile -Append
}
Logically the Get-ChildItem needs to be in front of the loop?! But I'm not that firm to edit the beginning of the loop correctly.
Upvotes: 0
Reputation: 3236
You need to include logging part to your script. You can make foreach loop
for every item that needs to be removed and write down activity to log file. Here is an example:
$LogFile = 'C:\log.txt'
dir "C:\Users\sam\Desktop\Files_todelete\*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } |
ForEach-Object {
Remove-Item $_.FullName -Recurse
Out-File -InputObject $('Removed {0}' -f $_.FullName) -FilePath $LogFile -Append
}
Upvotes: 1