A Twitter user asked for a script to remove old backups, and I had one I built back in February, so here it is (use at your own risk):
#rmbackup.ps1
# Removes database and transaction log backups
#
# Change log:
# February 2, 2010: Allen White
# Initial Version
# Get the SQL Server instance name from the command line
param(
[string]$inst=$null,
[int]$days=$null
)
# Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries
$v = [System.Reflection.Assembly]::LoadWithPartialName( 'Microsoft.SqlServer.SMO')
if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | out-null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SQLWMIManagement') | out-null
}
# Handle any errors that occur
Function Error_Handler {
Write-Host "Error Category: " + $error[0].CategoryInfo.Category
Write-Host " Error Object: " + $error[0].TargetObject
Write-Host " Error Message: " + $error[0].Exception.Message
Write-Host " Error Message: " + $error[0].FullyQualifiedErrorId
}
Trap {
# Handle the error
Error_Handler;
# End the script.
break
}
# Connect to the specified instance
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $inst
# Get the directory where backups are stored
$bkdir = $s.Settings.BackupDirectory
$retdays = $days * -1
# Delete the backup files
Get-ChildItem $bkdir -recurse -include *.bak | Where {($_.CreationTime -le $(Get-Date).AddDays($retdays))} | Remove-Item -Force
# Delete the transaction log files
Get-ChildItem $bkdir -recurse -include *.trn | Where {($_.CreationTime -le $(Get-Date).AddDays($retdays))} | Remove-Item -Force
Allen