PowerShell/scripts/remove-old-dirs.ps1

46 lines
1.6 KiB
PowerShell
Raw Normal View History

2024-10-01 15:24:16 +02:00
<#
2023-05-15 09:25:46 +02:00
.SYNOPSIS
Removes old directories
.DESCRIPTION
2023-06-20 14:50:43 +02:00
This PowerShell script removes any subfolder in a parent folder older than <numDays> (using last write time).
2023-05-15 09:25:46 +02:00
.PARAMETER path
2023-06-20 14:50:43 +02:00
Specifies the file path to the parent folder
2023-05-15 09:25:46 +02:00
.PARAMETER numDays
Specifies the number of days (1000 by default)
.EXAMPLE
PS> ./remove-old-dirs.ps1 C:\Temp 90
2025-01-14 16:26:21 +01:00
.LINK
https://github.com/fleschutz/PowerShell
2023-05-15 09:25:46 +02:00
.NOTES
2025-01-14 16:26:21 +01:00
Author: Markus Fleschutz | License: CC0
2023-05-15 09:25:46 +02:00
#>
param([string]$path = "", [int]$numDays = 1000)
try {
2023-06-20 14:50:43 +02:00
if ("$path" -eq "") { $path = Read-Host "Enter the file path to the parent folder" }
2025-01-14 16:35:32 +01:00
$stopWatch = [system.diagnostics.stopwatch]::startNew()
2023-05-15 09:25:46 +02:00
if (!(Test-Path -Path "$path" -PathType container)) { throw "Given path doesn't exist - enter a valid path, please" }
2025-01-14 16:26:21 +01:00
Write-Host "⏳ Searching for subfolders at '$path' older than $numDays days..."
$numRemoved = $numSkipped = 0
2023-06-20 14:50:43 +02:00
$folders = Get-ChildItem -path "$path" -directory
2023-05-15 09:25:46 +02:00
foreach ($folder in $folders) {
[datetime]$folderDate = ($folder | Get-ItemProperty -Name LastWriteTime).LastWriteTime
if ($folderDate -lt (Get-Date).AddDays(-$numDays)) {
2025-01-14 16:26:21 +01:00
Write-Host "Removing old '$folder'..."
2023-06-20 14:50:43 +02:00
$fullPath = $folder | Select-Object -ExpandProperty FullName
Remove-Item -path "$fullPath" -force -recurse
2023-05-15 09:25:46 +02:00
$numRemoved++
2023-06-20 14:50:43 +02:00
} else {
2025-01-14 16:26:21 +01:00
$numSkipped++
2023-05-15 09:25:46 +02:00
}
2023-06-20 14:50:43 +02:00
}
2023-05-15 09:25:46 +02:00
[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
2025-01-14 16:26:21 +01:00
"✅ Removed $numRemoved subfolders older than $numDays days in $($elapsed)s ($numSkipped skipped)."
2023-05-15 09:25:46 +02:00
exit 0 # success
} catch {
2023-06-20 14:50:43 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
2023-05-15 09:25:46 +02:00
}