Added Orphaned file script

This commit is contained in:
Brad Ganley 2024-09-09 14:10:28 -05:00
commit 4e7b0ed2cf

59
orphanFileAdjudicator.ps1 Normal file
View File

@ -0,0 +1,59 @@
# Say a directory
$directory = Read-Host "Please enter the directory to scan"
#Cuttoff days
$numberOfDays = Read-Host "Maximum desired file age in days"
# Is the directory a directory
if (-Not (Test-Path $directory)) {
Write-Host "The directory does not exist."
pause
exit
}
# WHEN IS IT
$currentDate = Get-Date
# Do the Math
$totalSize = Get-ChildItem -Path $directory -Recurse |
Where-Object { $_.LastWriteTime -lt $currentDate.AddDays(-$numberOfDays) -and -not $_.PSIsContainer } |
Measure-Object -Property Length -Sum
# Make it MB
$totalSizeMB = [math]::round($totalSize.Sum / 1MB, 2)
# Output the total size in megabytes
Write-Host "Total size of files older than $numberOfDays days: $totalSizeMB MB"
# Gather items (both files and folders) older than the specified number of days
$items = Get-ChildItem -Path $directory -Recurse |
Where-Object { $_.LastWriteTime -lt $currentDate.AddDays(-$numberOfDays) }
# Check if any items were found
if ($items.Count -eq 0) {
Write-Host "No items older than $numberOfDays days."
Write-Host "Press any key to exit..."
pause
exit
}
# Take the shot
$deleteItems = Read-Host "Do you want to delete these items? (y/n)"
if ($deleteItems -eq 'y') {
# cover fire
foreach ($item in $items) {
try {
Remove-Item -Path $item.FullName -Recurse -Force
Write-Host "Deleted: $($item.FullName)"
} catch {
Write-Host "Failed to delete: $($item.FullName)"
}
}
Write-Host "It is finished."
} else {
Write-Host "No items were deleted."
}
# We did it you guys
Write-Host "Press any key to exit..."
pause