mirror of
https://github.com/fleschutz/PowerShell.git
synced 2024-11-27 02:14:31 +01:00
2.8 KiB
2.8 KiB
The remove-old-dirs.ps1 Script
This PowerShell script removes any directory in a given folder older than (using last write time).
Parameters
/home/mf/Repos/PowerShell/Scripts/remove-old-dirs.ps1 [[-path] <String>] [[-numDays] <Int32>] [<CommonParameters>]
-path <String>
Specifies the file path to the folder
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-numDays <Int32>
Specifies the number of days (1000 by default)
Required? false
Position? 2
Default value 1000
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
Example
PS> ./remove-old-dirs.ps1 C:\Temp 90
Notes
Author: Markus Fleschutz
Source Code
<#
.SYNOPSIS
Removes old directories
.DESCRIPTION
This PowerShell script removes any directory in a given folder older than <numDays> (using last write time).
.PARAMETER path
Specifies the file path to the folder
.PARAMETER numDays
Specifies the number of days (1000 by default)
.EXAMPLE
PS> ./remove-old-dirs.ps1 C:\Temp 90
.NOTES
Author: Markus Fleschutz
#>
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 (!(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
$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
$numRemoved++
} 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"
exit 0 # success
} catch {
Write-Error "ERROR in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1 # failure
}
Generated by convert-ps2md.ps1 using the comment-based help of remove-old-dirs.ps1