• I use the following stored proc to delete old backup files as a step within a standard scheduled job.

    usage: usp_DeleteOldBackupFiles <path>, <file extention>, <age_hours>

    i.e. usp_DeleteOldBackupFiles 'D:\MSSQL_DBBackups', 'bak', 36

    usp_DeleteOldBackupFiles 'D:\MSSQL_DBBackupsLogs', 'trn', 72

    --====================================================================

    CREATE PROCEDURE [dbo].[usp_DeleteOldBackupFiles]

    @path nvarchar(256),

    @extention nvarchar(10),

    @age_hrs int

    AS

    BEGIN

    SET NOCOUNT ON;

    DECLARE @DeleteDate nvarchar(50)

    DECLARE @DeleteDateTime datetime

    SET @DeleteDateTime = DateAdd(hh, -@age_hrs, GetDate())

    SET @DeleteDate = (Select Replace(Convert(nvarchar, @DeleteDateTime, 111), '/', '-') + 'T' + Convert(nvarchar, @DeleteDateTime, 108))

    EXECUTE master.dbo.xp_delete_file 0, @path, @extention, @DeleteDate, 1

    END

    --============================

    -- xp_delete_file information

    --============================

    -- xp_delete_file actually checks the file header to see what type of file it is and will only delete certain types such

    -- as database and log backups. I suppose they expanded this to certain types of log files as well but as you say this is

    -- not documented by MS. Just be aware that it will not delete just any file type

    -- First argument is:

    -- 0 - specifies a backup file

    -- 1 - specifies a report file

    -- (I'm not sure what the difference between a "backup file" and a "report file" is, since you specify the extension of files

    -- you're deleting with the third argument.)

    --

    -- Fifth argument is whether to delete recursively.

    -- 0 - don't delete recursively (default)

    -- 1 - delete files in sub directories

    --====================================================================

    I tweeked this from information I found on the net - Unfortunately, I can't remember where from so can't offer credit where it's due 🙁

    Cheers