Who doesn’t love cleaning up old files, don’t worry, Powershell comes to the rescue.

We all know that shared network drives collect all kind of garbage, and usually around 90% could actually be missed.

I’ve recently been working on cleaning up files which were created a long time ago, thanks to Powershell, we can script this action and make Powershell work for us.

What I do here is to look at the creation date of the files and delete them if they are older than 2 years old, so we set a limit to target only those who are old enough to be removed.

I recommend having backup of the files before running these Powershell scripts.

Logging the output is also recommending

# Set some variables
$Limit = (Get-Date).AddYears(-2) # Set the limit for removing files to 2 years
$Path = "C:\Temp" # Set the path to process
$LogPath = "C:\Temp\Logs" # Set the path for the Log
$LogDate = Get-Date -Format dd_MM_yyyy # Set the Date format for the log file name
$RemoveFiles = (Get-ChildItem -Path $Path -Recurse | Where { $_.CreationTime -lt $Limit -and $_.PSIsContainer -eq $false }) # Collect the files to remove into an array
# Check if the LogPath exists, if not create it
if(!(Test-Path $LogPath)) {
New-Item $LogPath -ItemType Directory
}
# Process the files and log the output
Foreach($file in $RemoveFiles) {
$file.FullName + " was created " + $file.CreationTime | Out-File "$LogPath\$LogDate`-RemoveFiles.log" -Encoding unicode -Append
Remove-Item $file.FullName -Force
}

Use scheduled tasks to run the script to do regular cleanup of old files.

More to come in upcoming series.

Hallgrimur #TheMachine