The *remove-old-dirs.ps1* Script =========================== This PowerShell script removes any subfolder in a parent folder older than (using last write time). Parameters ---------- ```powershell /Repos/PowerShell/scripts/remove-old-dirs.ps1 [[-path] ] [[-numDays] ] [] -path Specifies the file path to the parent folder Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -numDays Specifies the number of days (1000 by default) Required? false Position? 2 Default value 1000 Accept pipeline input? false Accept wildcard characters? false [] This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. ``` Example ------- ```powershell PS> ./remove-old-dirs.ps1 C:\Temp 90 ``` Notes ----- Author: Markus Fleschutz | License: CC0 Related Links ------------- https://github.com/fleschutz/PowerShell Script Content -------------- ```powershell <# .SYNOPSIS Removes old directories .DESCRIPTION This PowerShell script removes any subfolder in a parent folder older than (using last write time). .PARAMETER path Specifies the file path to the parent folder .PARAMETER numDays Specifies the number of days (1000 by default) .EXAMPLE PS> ./remove-old-dirs.ps1 C:\Temp 90 .LINK https://github.com/fleschutz/PowerShell .NOTES Author: Markus Fleschutz | License: CC0 #> 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 for subfolders at '$path' older than $numDays days..." $numRemoved = $numSkipped = 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++ } else { $numSkipped++ } } [int]$elapsed = $stopWatch.Elapsed.TotalSeconds "✅ Removed $numRemoved subfolders older than $numDays days in $($elapsed)s ($numSkipped skipped)." exit 0 # success } catch { "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])" exit 1 } ``` *(page generated by convert-ps2md.ps1 as of 01/17/2025 08:37:11)*