mirror of
https://github.com/fleschutz/PowerShell.git
synced 2024-11-29 11:24:27 +01:00
Update remove-old-dirs.ps1
This commit is contained in:
parent
e17d4ed9ab
commit
7aff4198d9
@ -1,10 +1,10 @@
|
||||
<#
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Removes old directories
|
||||
.DESCRIPTION
|
||||
This PowerShell script removes any directory in a given folder older than <numDays> (using last write time).
|
||||
This PowerShell script removes any subfolder in a parent folder older than <numDays> (using last write time).
|
||||
.PARAMETER path
|
||||
Specifies the file path to the folder
|
||||
Specifies the file path to the parent folder
|
||||
.PARAMETER numDays
|
||||
Specifies the number of days (1000 by default)
|
||||
.EXAMPLE
|
||||
@ -17,30 +17,29 @@ param([string]$path = "", [int]$numDays = 1000)
|
||||
|
||||
try {
|
||||
$stopWatch = [system.diagnostics.stopwatch]::startNew()
|
||||
if ("$path" -eq "") { $path = Read-Host "Enter the file path to the directory" }
|
||||
if ("$path" -eq "") { $path = Read-Host "Enter the file path to the parent folder" }
|
||||
if (!(Test-Path -Path "$path" -PathType container)) { throw "Given path doesn't exist - enter a valid path, please" }
|
||||
|
||||
Write-Progress "Removing old directories in $path..."
|
||||
$folders = Get-ChildItem -Path "$path" -Directory
|
||||
Write-Host "⏳ Removing subfolders older than $numDays days in $path..."
|
||||
$folders = Get-ChildItem -path "$path" -directory
|
||||
$numRemoved = 0
|
||||
$count = 0
|
||||
foreach ($folder in $folders) {
|
||||
[datetime]$folderDate = ($folder | Get-ItemProperty -Name LastWriteTime).LastWriteTime
|
||||
$count++
|
||||
if ($folderDate -lt (Get-Date).AddDays(-$numDays)) {
|
||||
Write-Host "#$($count): Removing old '$folder'..."
|
||||
$fullPath = $folder | Select-Object -ExpandProperty FullName
|
||||
Remove-Item -Path $fullPath -Force -Recurse
|
||||
Write-Host "($($count)) Removing old '$folder'..."
|
||||
$fullPath = $folder | Select-Object -ExpandProperty FullName
|
||||
Remove-Item -path "$fullPath" -force -recurse
|
||||
$numRemoved++
|
||||
} else {
|
||||
Write-Host "#$($count): Skipping young '$folder'..."
|
||||
} else {
|
||||
Write-Host "($($count)) Skipping young '$folder'..."
|
||||
}
|
||||
}
|
||||
Write-Progress -completed "."
|
||||
}
|
||||
[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
|
||||
Write-Host "Removed $numRemoved of $count directories older than $numDays days at $path in $elapsed sec"
|
||||
"✔️ Removed $numRemoved of $count subfolders older than $numDays days in $elapsed sec"
|
||||
exit 0 # success
|
||||
} catch {
|
||||
Write-Error "ERROR in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
|
||||
exit 1 # failure
|
||||
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
|
||||
exit 1
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user