Posted On May 6, 2022

PowerShell: Delete Files Older Than 30 Days

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Delete Files Older Than 30 Days

Have you ever run into C:\ volumes reaching critical thresholds because certain applications or users filling up system drive, causing Windoze to run out of disk space and perform sluggishly? Well, you’re in luck:

# deleteLogsOlderThanXDays.ps1
# Version 0.0.1

# User defined variables
$logDirectories='C:\Temp'
$deleteLogsOlderThanDays=30
$testOnly=$false
$logFile='C:\purgedFiles.txt'
$renameLogGreaterThanMb=5

# Execute deletion
# Safety check
$hardStopLocations=@(
	'C:\Windows',
	'C:\ProgramData',
	'C:\Users',
	'C:\Program Files (x86)',
	'C:\Program Files'
	)
$ErrorActionPreference='ignore'
$today=Get-Date
$deletionMarker=$today.AddDays(-$deleteLogsOlderThanDays)
$deletedFiles="`r`nJob started $($today.DateTime.ToString())`r`n--------------------------------------------`r`n"
foreach($directory in $logDirectories){
	$isSafe=.{
		$parent=if(test-path $directory){
				try{
					(get-item $directory -EA Ignore).parent.FullName
				}catch{
                    $null
                }
			}else{
				write-warning "$directory cannot be parsed."
				return $null
			}
		if($parent -eq $null){
				write-warning "$directory is invalid"
				return $false
		}elseif($parent -in $hardStopLocations){
			write-warning "$directory is not a safe location to manipulate files."
			return $false
		}else{
			return $true
		}
	}
	if($isSafe){
		if($testOnly){
			Get-ChildItem $directory -Recurse -EA Ignore|?{ $_.LastWriteTime -lt $deletionMarker }|%{write-host "Marked for deletion: $_"}
		}else{			
			$itemsToDelete=Get-ChildItem $directory -Recurse -EA Ignore|?{$_.LastWriteTime -lt $deletionMarker}
			if($itemsToDelete){
				foreach ($item in $itemsToDelete){
					try{
						Remove-Item $item.fullname -ea stop
						write-host "Deleted: $item"
						$deletedFiles+="Deleted: $($item.Fullname) with lastWriteTime of $($item.LastWriteTime.toString())`r`n"
					}catch{
						write-warning $_
					}
				}		
			}else{
                $comment="There are no item(s) to delete in $directory`r`n"
				write-host $comment
                $deletedFiles+=$comment
			}
		}
	}
}
$deletedFiles+="--------------------------------------------`r`nJob ended $((get-date).DateTime.ToString())"
if(test-path $logFile){
    $logFileInfo=get-item $logFile
    if($logFileInfo.length/1MB -gt $renameLogGreaterThanMb){
        $timeZoneName=[System.TimeZoneInfo]::Local.StandardName
        $timeStampFileName=[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow,$timeZoneName).ToString('yyyy-MM-dd_HH-mm-ss')+'_'+[regex]::replace($timeZoneName,'([A-Z])\w+\s*', '$1')
        $abbreviatedZoneName=if($timeZoneName -match ' '){[regex]::replace($timeZoneName,'([A-Z])\w+\s*', '$1')}else{$timeZoneName}
        $timeStampFormat="yyyy-MM-dd_HH-mm-ss_$abbreviatedZoneName"
        $timeStampFileName=[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow,$timeZoneName).ToString($timeStampFormat)
        $newName=join-path $logFileInfo.DirectoryName $($logFileInfo.BaseName+"_$timeStampFileName"+$logFileInfo.Extension)
        rename-item $logFile $newName
    }
}
Add-Content $logFile $deletedFiles
write-host "Log has been written to $logFile"

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Basic HTML and HTML5: Add a Submit Button to a Form

<h2>CatPhotoApp</h2><main><p>Click here to view more <a href="#">cat photos</a>.</p><a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying…

PowerShell: Time Stamp Variable

This is useful in almost any script as it enables the accurate timestamp of log…

Script to Disable User Accounts

accountsToDisable.txtorangeapplepeartermed user REM disableAccounts.batREM read accountsToDisable.txt and convert names into proper DN entries. Save result…
Other project: DragonCoin.com