|
| 1 | +# This script is designed to fix access denied errors when cleaning up log files. |
| 2 | +# It attempts to delete log files and handles access denied errors by taking ownership of the files and retrying the deletion. |
| 3 | + |
| 4 | +# Set the path to the log files and the number of days to keep the files. |
| 5 | +$logPath = "C:\Logs" |
| 6 | +$daysToKeep = 30 |
| 7 | +$limit = (Get-Date).AddDays(-$daysToKeep) |
| 8 | + |
| 9 | +# Function to take ownership of a file. |
| 10 | +function Take-Ownership { |
| 11 | + param ( |
| 12 | + [string]$filePath |
| 13 | + ) |
| 14 | + try { |
| 15 | + $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name |
| 16 | + $takeown = Start-Process -FilePath "takeown.exe" -ArgumentList "/F `"$filePath`"" -Wait -NoNewWindow -PassThru |
| 17 | + $icacls = Start-Process -FilePath "icacls.exe" -ArgumentList "`"$filePath`" /grant `$user`:F" -Wait -NoNewWindow -PassThru |
| 18 | + Write-Host "Ownership taken for file: $filePath" -ForegroundColor Green |
| 19 | + } catch { |
| 20 | + Write-Host "Error taking ownership of file: $filePath" -ForegroundColor Red |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +# Function to delete old log files and handle access denied errors. |
| 25 | +function Delete-OldLogs { |
| 26 | + param ( |
| 27 | + [string]$path, |
| 28 | + [datetime]$dateLimit |
| 29 | + ) |
| 30 | + try { |
| 31 | + Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $dateLimit } | ForEach-Object { |
| 32 | + try { |
| 33 | + Remove-Item -Path $_.FullName -Force |
| 34 | + Write-Host "Deleted file: $($_.FullName)" -ForegroundColor Green |
| 35 | + } catch { |
| 36 | + if ($_.Exception -match "Access to the path") { |
| 37 | + Write-Host "Access denied for file: $($_.FullName). Attempting to take ownership." -ForegroundColor Yellow |
| 38 | + Take-Ownership -filePath $_.FullName |
| 39 | + try { |
| 40 | + Remove-Item -Path $_.FullName -Force |
| 41 | + Write-Host "Deleted file after taking ownership: $($_.FullName)" -ForegroundColor Green |
| 42 | + } catch { |
| 43 | + Write-Host "Error deleting file after taking ownership: $($_.FullName)" -ForegroundColor Red |
| 44 | + } |
| 45 | + } else { |
| 46 | + Write-Host "Error deleting file: $($_.FullName)" -ForegroundColor Red |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } catch { |
| 51 | + Write-Host "Error processing log files in path: $path" -ForegroundColor Red |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +# Main script execution |
| 56 | +Write-Host "Starting log cleanup..." -ForegroundColor Cyan |
| 57 | +Delete-OldLogs -path $logPath -dateLimit $limit |
| 58 | +Write-Host "Log cleanup completed." -ForegroundColor Cyan |
0 commit comments