TSQL command to delete backup files older than N hours
Remember that T-SQL should not be used to do file maintenance. Instead you should use Powershell to delete /move / copy etc files.

Tsql way:

use xp_cmdshell command along with the FORFILES command

e.g Delete all .sql files in the C:\Backup directory and its subfolders where the file modified date is more than 30 days old.

EXEC xp_cmdshell 'FORFILES /p c:\BACKUP /s /m *.sql /d -30 /c "CMD /C del /Q /F @FILE"'


Disclaimer: Enabling xp_cmdshell is a security risk and not many companies allow it.

Powershell Way --> This should be the right approach !!

A full script can be found at technet.

## Delete files older than 90 days

$a = Get-ChildItem C:\Scripts
foreach($x in $a)
    {
        $y = ((Get-Date) - $x.CreationTime).Days
        if ($y -gt 90 -and $x.PsISContainer -ne $True)
            {$x.Delete()}
    }