Skip to content

Instantly share code, notes, and snippets.

@kkamegawa
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkamegawa/2acdf9db70630cd449d2 to your computer and use it in GitHub Desktop.
Save kkamegawa/2acdf9db70630cd449d2 to your computer and use it in GitHub Desktop.
Remove old SQL Server Transaction log, and Backup log, dump files.
#remove sql server old files
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")
#create a new server object
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
$backupDirectory = $server.BackupDirectory
$folders = get-childitem $backupDirectory -Directory
foreach($folder in $folders){
$fullpath = Join-Path $backupDirectory -ChildPath $folder
if((Get-ChildItem $fullpath -Filter *.trn ).Exists -eq $true){
$newesttime = (Get-ChildItem $fullpath -Filter *.bak | Sort-Object lastwritetime -Descending)[0].LastWriteTime
Get-ChildItem $fullpath -Filter *.trn | ForEach-Object { if($_.LastWriteTime -lt $newesttime){ remove-item $_.FullName }}
}
}
$logDirectory = $server.ErrorLogPath
$extensions = "*.txt","*.log","*.mdmp"
foreach($ext in $extensions){
Get-ChildItem $logDirectory -Recurse -Filter $ext | ForEach-Object { if($_.lastwritetime.adddays(3) -lt [Datetime]::Now) {remove-item $_.fullname }}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment