Skip to content

remove-old-dirs

Removes old directories

#Requires -Version 5.1

param([string]$path = "", [int]$numDays = 1000)

try {
	if ("$path" -eq "") { $path = Read-Host "Enter the file path to the parent folder" }
	$stopWatch = [system.diagnostics.stopwatch]::startNew()
	if (!(Test-Path -Path "$path" -PathType container)) { throw "Given path doesn't exist - enter a valid path, please" }

	Write-Host "⏳ Searching in '$path' for subfolders older than $numDays days..."
	$numRemoved = 0
	$folders = Get-ChildItem -path "$path" -directory
	foreach ($folder in $folders) {
		[datetime]$folderDate = ($folder | Get-ItemProperty -Name LastWriteTime).LastWriteTime
		if ($folderDate -lt (Get-Date).AddDays(-$numDays)) {
			Write-Host "⏳ Removing old '$folder'..."
			$fullPath = $folder | Select-Object -ExpandProperty FullName
			Remove-Item -path "$fullPath" -force -recurse
			$numRemoved++
		}
	}
	[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
	"✅ Removed $numRemoved of $($folders.Count) subfolders in $($elapsed)s."
	exit 0
} catch {
throw
}

Specifies the file path to the parent folder

Specifies the number of days (1000 by default)

An interactive directory of PowerShell scripts.