ps/Modules/Cole.PowerShell.Developer/Public/Clear-OldSqlLogs.ps1

50 lines
2.2 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
function Clear-OldSqlLogs {
<#
.SYNOPSIS
Will delete all files older than one month from today from any SQL Server installed on the computer
Warning: This method does not care about the file contents, it will try to delete it if it is older than 1 month.
If you use the WhatIfPreference it will try to honor that and not delete things, but I have not tested it with -WhatIf and -Force
This enumerates all subfolders called MSSQL under C:\Program Files\Microsoft SQL Server\ (the typical location and name for SQL server installs) and looks for a Log folder under that
If you have installed in a non-standard way, this will not help.
This function is NOT polite. Only use it if you are sure you want to delete things brutally.
.PARAMETER Force
Force the file deletion
#>
[CmdletBinding()]
param (
[switch]$Force
)
Write-Host "This function may have errors if you do not have read or modify permissions on the appropriate files in this folder. Please reach out to cbrand to update this file."
$MSSqlFolders = Get-ChildItem 'C:\Program Files\Microsoft SQL Server\' -Include 'MSSQL' -Recurse
$oneMonthAgo = [System.DateTime]::Now.AddMonths(-1)
foreach ($msSqlFolder in $MSSqlFolders) {
$folderPath = $msSqlFolder.FullName
Write-Host "Found $folderPath"
$logsFolder = Join-Path -Path $folderPath -ChildPath 'Log'
if (Test-Path -Path $logsFolder) {
Write-Host "Found a logs folder at [$logsFolder]. Will attempt to clean it."
$SqlServerLogFiles = Get-ChildItem -Path $logsFolder
$oldFiles = $SqlServerLogFiles.Where({ $_.LastWriteTime -lt $oneMonthAgo })
foreach ($file in $oldFiles) {
$fullName = $file.FullName
try {
Write-Host "Will remove file at $fullName"
Remove-FileSystemItem -Path $fullName -WhatIf:$WhatIfPreference -Force:$Force
} catch {
Write-Warning "Was not able to delete the file at [$fullName]. You may not have permission."
Write-Warning $_.Exception.Message
}
}
} else {
Write-Host "Did not find or could not access $logsFolder"
}
}
}