Powershell to clean-up (delete/purge/archive) old BizTalk log/debug files

In the place where I work, we have numerous SendPorts that we sometimes enable that create copies of BizTalk messages on the disk, in a directory called D:\MessageLog (with various sub-directories).

Rarely do we need to go back more than 2 or 3 days to see these files.

We have a Powershell script in place to help clean-up these files. We are a very high volume system, and we can end up with tens or hundreds of thousands of these messages in a few days.

PowerShell 3.0 and higher

#All files older than x days in D:\MessageLog
GET-CHILDITEM "D:\MessageLog" -RECURSE -FILE | Where  LastWriteTime -lt  (Get-Date).AddDays(-3) | REMOVE-ITEM -force

Parameterize it like this

#All files older than x days in D:\MessageLog
$keepDays = $args[0]  #allow the parm to be passed from the command line in an argument 
$DirName = "D:\MessageLog"
if ($keepDays -eq $null) {$keepDays = 15 } #set some default if no argument is passed 
#note the negative sign in front of $keepDays 
GET-CHILDITEM $DirName -RECURSE -FILE | Where  LastWriteTime -lt  (Get-Date).AddDays(-$keepDays) | REMOVE-ITEM -force

Or you instead of cramming everything on one line, you can do it this way, and include 
various Write-Host statements to help you debug 

foreach ($file in $files)
   Write-Host $file.LastWriteTime 
   if ($file.LastWriteTime.AddDays($keepDays) -lt (GET-Date))
       Write-Host "$file.Basename will be deleted" 
       Remove-Item $file.fullname -force 

NOTE: For older release of PowerShell, before 3.0 I think, you have to use the “-and -not $_.psiscontainer” to limit what it returns to just files.

#All files older than x days in D:\MessageLog
# $_.PsIsContainer tells you that you have a folder
GET-CHILDITEM D:\MessageLog -RECURSE| Where { $_.LastWriteTime.AddDays(2) -lt (GET-DATE) -and -not $_.psiscontainer} |% {REMOVE-ITEM $_.fullname -force}

This script could be scheduled by Windows Task Manager. To make things easier, I usually create a one line .bat or .cmd file like the one below. The scheduler simple executes the .cmd file.

powershell -command "& 'CleanupMessageLog.ps1'"

or if the Ampersand gives you errors, try
powershell -command ". 'e:\Projects\MyApp\CleanupMessageLog.ps1'"

NOTE: Put the folder name in double quotes if it contains any embedded spaces.

Compare to VBScript cleanup/delete files script.


Leave a Reply