As our business continues to focus on providing white labeled Tier 3 IT support services, RMM as a service, and co-managed IT services this blog will be highlighting tips for RMM automation. Here is a script that we came up with to handle a particular client that has a Line-of-Business application that does automatic backups to the server but it does not clean up after itself which leads to a full server hard drive. We have tailored this script to be used not only at that client but for any folder on any Microsoft Windows computer for any number of days previous and for any specified file extension. This script could easily be modified to take any action on files in a folder older than a specific date, like copy them to off-site storage bucket in Amazon Glacier.
Variables
Here are the variables we are using for this script:
- $DaysAgo = the number of days ago or older that you want deleted
- $FileExtension = the extension for the files that are to be deleted or leave blank for all files
- $FolderPath = the full local file path that is to be cleaned
Script Snippet
# Defines the 'days old' (today's date minus DaysAgo)
$days = -($DaysAgo)
$age = (Get-Date).AddDays($days)
# Get all the files in the folder and subfolders matching extension | foreach file
if ($FileExtension -ne '') {
Get-ChildItem $FolderPath -Recurse -File | Where-Object { $_.Extension -eq $FileExtension } | foreach{
# if creationtime is 'le' (less or equal) than DaysAgo days
if ($_.CreationTime -le $age){
Write-Output "Older than $DaysAgo days - $($_.name)"
# remove the item
Remove-Item $_.fullname -Force -Verbose
}
}
}else {
Get-ChildItem $FolderPath -Recurse -File | foreach{
# if creationtime is 'le' (less or equal) than DaysAgo days
if ($_.CreationTime -le $age){
Write-Output "Older than $DaysAgo days - $($_.name)"
# remove the item
Remove-Item $_.fullname -Force -Verbose
}
}
}
This script is destructive meaning that the files deleted are gone for good, so be careful with this one. Notice that we put in some output that will declare a file older than $DaysAgo and then delete it giving the details of the delete. This give a record of what was deleted. We have thought also about adding a counter for total amount of file space deleted, but making it human readable is not simple code.
If your company is a MSP or wants to become one and automation just seems out of reach, then contact us to run your RMM for you.