Skip to content

Instantly share code, notes, and snippets.

@drlsdee
Created March 30, 2023 09:56
Show Gist options
  • Save drlsdee/9d7d4efd42c8e98948ccf743decc6fde to your computer and use it in GitHub Desktop.
Save drlsdee/9d7d4efd42c8e98948ccf743decc6fde to your computer and use it in GitHub Desktop.
Returns filesystem entries older than N days
function Get-OldItem {
[CmdletBinding()]
[OutputType([System.IO.FileSystemInfo])]
param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[System.IO.FileSystemInfo]
$Path,
[Parameter()]
[int]
$Days = 30,
[Parameter()]
[ValidateSet('CreationTime','LastAccessTime','LastWriteTime','CreationTimeUtc','LastAccessTimeUtc','LastWriteTimeUtc')]
[string]
$Property = 'LastWriteTimeUtc'
)
begin {
if ($Property.EndsWith('Utc',[System.StringComparison]::InvariantCultureIgnoreCase)) {
[datetime]$dateToCompare = [datetime]::UtcNow.Date.AddDays(-$Days)
}
else {
[datetime]$dateToCompare = [datetime]::Now.Date.AddDays(-$Days)
}
}
process {
if (-not $Path.Exists) { return }
[datetime]$dateOfItem = $Path.$Property
[int]$comparisonResult = $dateToCompare.CompareTo($dateOfItem)
[bool]$isOlderThan = $comparisonResult -ge 0
<#
switch ($comparisonResult) {
-1 { [System.ConsoleColor]$fgColor = [System.ConsoleColor]::Magenta }
0 { [System.ConsoleColor]$fgColor = [System.ConsoleColor]::White }
1 { [System.ConsoleColor]$fgColor = [System.ConsoleColor]::Cyan }
Default { [System.ConsoleColor]$fgColor = [System.ConsoleColor]::Yellow }
}
[string]$stringToShow = 'Base: {0:yyyy.MM.dd}; Current: {1:yyyy.MM.dd}; Is older: {2}; Path: {3}' -f $dateToCompare,$dateOfItem,$isOlderThan,$Path.FullName
Write-Host -ForegroundColor $fgColor -Object $stringToShow
#>
if (-not $isOlderThan) { return }
return $Path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment