Last active
May 6, 2020 10:07
-
-
Save WimObiwan/e04d2e18c84161e2651260f4df701c07 to your computer and use it in GitHub Desktop.
Remove-OldItems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original script located at https://gist.github.com/WimObiwan/e04d2e18c84161e2651260f4df701c07 | |
# https://stackoverflow.com/a/40887001 | |
function DisplayInBytes($num) | |
{ | |
$suffix = "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" | |
$index = 0 | |
while ($num -gt 1kb) | |
{ | |
$num = $num / 1kb | |
$index++ | |
} | |
"{0:N1} {1}" -f $num, $suffix[$index] | |
} | |
function Remove-OldItems { | |
[CmdletBinding(SupportsShouldProcess = $true)] | |
param ( | |
# Specifies a path to one or more locations. Wildcards are permitted. | |
[Parameter(Mandatory=$true, | |
ValueFromPipeline=$true, | |
ValueFromPipelineByPropertyName=$true, | |
HelpMessage="Path to one or more locations.")] | |
[ValidateNotNullOrEmpty()] | |
[SupportsWildcards()] | |
[string[]] | |
$Path, | |
[switch] | |
$Recurse, | |
[int] | |
$RemoveDaysLastWriteTime = -1, | |
[switch] | |
$RemoveEmptyDirectories = $false | |
) | |
begin { | |
[long]$totalSize = 0 | |
} | |
process { | |
if ($RemoveDaysLastWriteTime -ge 0) { | |
Get-ChildItem -File -Recurse:$Recurse $Path ` | |
| Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RemoveDaysLastWriteTime) } ` | |
| %{ $totalSize += $_.Length; $_ | Remove-Item } | |
} | |
if ($RemoveEmptyDirectories) { | |
Get-ChildItem -Directory -Recurse:$Recurse $Path | Sort-Object FullName | Where-Object { | |
if (@(Get-ChildItem $_.FullName).Count -eq 0) { | |
Remove-Item $_.FullName | |
} | |
} | |
} | |
} | |
end { | |
Write-Warning "Removed $totalSize bytes ($(DisplayInBytes $totalSize))" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment