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

JavaScript: Build a Tic Tac Toe Game (without AI)

Demo: https://blog.kimconnect.com/wp-content/projects/ticTacToeGame.html CSS Code: @import url('https://fonts.googleapis.com/css?family=Merienda');body{ font-family: 'Merienda', cursive; font-weight: bold;}#gameBoard { width: 396px; //…

PowerShell: Add System Backup Privileges

function addSystemPrivilege{ param( [String[]]$privileges=@("SeBackupPrivilege","SeRestorePrivilege") ) function includeSystemPrivileges{ $win32api = @' using System; using System.Runtime.InteropServices; namespace…

Quick Script to Mount Remote UNC Paths as Local Drive Letters

Simple Mount: # Mapping a drive $username='domain\testAdmin' $password='PASSWORD' $remotePath='\\UNCSERVER\SHAREPATH\Backup' $unavailableDriveLetters=(Get-Volume).DriveLetter|sort $availableDriveLetters=.{(65..90|%{[char]$_})|?{$_ -notin $unavailableDriveLetters}} [char]$firstAvailableDriveLetter=$availableDriveLetters[0] $command="net…