Technical Article

Cleanup old text files on the errorlog directory

,

I have a lot of .txt files on the errorlog directory, coming from jobstep output. I want to delete all old .txt files on a regularly basis.

I noticed that a Maintenance Cleanup Task to clean Maintenance Plan text reports does not cleanup jobstep output text files. Apparantly the procedure xp_delete_file (used by this task) can only delete Maintenance Plan text files and not Jobstep output text files.

After puzzling a while I managed to write a small generic Powershell script that works in a jobstep. Of course the jobstep has to be of the type "PowerShell". I tested it on sql2008R2 and sql2014.

What does it do?

It deletes *.txt files older than 90 days on the errrlog directory of the default instance of the user where the job is running under. Mostly this is the SQL Agent service owner.

How to implement it?

Create a job. Create a  step with type PowerShell. Paste the code into the Command window. Adjust the $Days variable. Create a (weekly) schedule and you're done.

Always test new code first on a testenvironment!

Gerrit Mantel, LUMC, The Netherlands

$Server = "$(ESCAPE_DQUOTE(SRVR))"
$Sql=@"
SELECT REPLACE(CONVERT(NVARCHAR(256),SERVERPROPERTY('ErrorLogFileName')),'\ERRORLOG','') AS Path
"@
$Sqlvar = Invoke-Sqlcmd -Query $Sql -ServerInstance $Server
Write-Output "Path:" $Sqlvar.Path

$Mask = "*.txt"
Write-Output "Mask:" $Mask

$Days = 90
Write-Output "Days:" $Days

$Now = Get-Date
$Cutoffdate = $Now.AddDays(-$Days)
$Files = Get-Childitem $Sqlvar.Path -Include $Mask -Recurse | Where {$_.LastWriteTime -le "$Cutoffdate"}
foreach ($File in $Files) { if ($File -ne $NULL) { Remove-Item $File.FullName } }

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating