McBin

file age

function Test-FileAgeOlderThan21Days {
    param (
        [Parameter(Mandatory=$true)]
        [string]$FilePath
    )

    if (-not (Test-Path $FilePath)) {
        Write-Error "File not found: $FilePath"
        return $false # Or handle as per your requirement if the file doesn't exist
    }

    $fileInfo = Get-Item $FilePath
    $lastWriteTime = $fileInfo.LastWriteTime
    $cutoffDate = (Get-Date).AddDays(-21)

    if ($lastWriteTime -lt $cutoffDate) {
        $true
    } else {
        $false
    }
}

# --- Examples of how to use the function ---

# Example 1: Check a file that is likely older than 21 days (replace with a real path)
# Create a dummy file that is clearly old for testing
$oldFilePath = "C:\Temp\OldFile.txt" # Change this to a path you can write to
if (-not (Test-Path "C:\Temp")) { New-Item -Path "C:\Temp" -ItemType Directory | Out-Null }
Set-Content -Path $oldFilePath -Value "This is an old file."
(Get-Item $oldFilePath).LastWriteTime = (Get-Date).AddDays(-30) # Manually set to 30 days ago

Write-Host "Is '$oldFilePath' older than 21 days? $(Test-FileAgeOlderThan21Days -FilePath $oldFilePath)"

# Example 2: Check a file that is likely NOT older than 21 days (replace with a real path)
# Create a dummy file that is recent for testing
$recentFilePath = "C:\Temp\RecentFile.txt" # Change this to a path you can write to
Set-Content -Path $recentFilePath -Value "This is a recent file."
# Its creation/modification time will be current, so it should not be older than 21 days

Write-Host "Is '$recentFilePath' older than 21 days? $(Test-FileAgeOlderThan21Days -FilePath $recentFilePath)"

# Example 3: Check a non-existent file
Write-Host "Is 'C:\NonExistentFile.txt' older than 21 days? $(Test-FileAgeOlderThan21Days -FilePath 'C:\NonExistentFile.txt')"

# Clean up dummy files (optional)
Remove-Item $oldFilePath -ErrorAction SilentlyContinue
Remove-Item $recentFilePath -ErrorAction SilentlyContinue
Copied to clipboard!