PowerShell Delete Files Older than 15 days or more, when there is a need to delete file older than 7 days or 15 days on the multiple remote computers here are the scripts that do the same thing.
In my example, I want to delete files under C:\apps\logs
$oldfiles = Get-childitem -path "C:\apps\logs" -directory | where-object {$_.LastwriteTime -lt (get-date).AddDays(-15) } #Now remove these old files $oldfiles | Remove-Item -force - Recurse
You can also write this in a single line code
Get-childitem -path "C:\apps\logs" -directory | where-object {$_.LastwriteTime -lt (get-date).AddDays(-15) } | | Remove-Item -force - Recurse
If you want to do it the same on a single remote machine, here is how the code looks.
$oldfiles = Get-Childitem -path "C:\apps\logs" -directory | where-object {$_.LastwriteTime -lt (get-date).AddDays(-15) } # now you need to mention the remote machine name in the code Remove-Item -Path "Machine1\C$\$oldfiles" -Recurse -Force
The above codes delete the logs file older than 15 days on the remote server Machine1
When you want Delete on Multiple remote Machines, here is how the code looks.
Let’s check it Multiple Remote Machines
we need to create one more file for storing the all the servers or multiple machines, I named it Allserver.txt storing it in my local machine c:\temp\Allserver.tx
The above code deletes the files and directories under C:\apps\logs which are older than 15 days on the remote machines that you have mentioned in the text file allserver.txt.
Note: if you want to change the older file days like 7 or 30 as per your need, then you can simply change this part (get-date).AddDays(-7) or (get-date).AddDays(-30) in code.
Thank you for reading this article, if you have any questions please let us know.
Thank you for visiting my site, for any scripts in these articles you are testing please make sure you have tested this script in our lower environment before you run in production.
$servers = Get-Content -Path "C:\temp\AllServer.txt"
Foreach ($server in $servers)
{ $oldfiles = Get-Childitem -path "C:\apps\logs" -directory | where-object {$_.LastwriteTime -lt (get-date).AddDays(-15)
}
Foreach ($onefile in $oldfiles)
{
Remove-Item -Path "\\$server\c$\onefile" | -Recurse -Force -verbose }
}
Leave a Reply Cancel reply