1

I'm trying to delete a directory (3gb) after a TFSBuild finishes. I put the task in a try finally block so that it always executes. Problem is when a build is manually stopped, the task is killed if it takes >1 min or so. TFSBuild thinks that the build is hanging because it's taking so long to stop.

I've tried the following to no avail:

    static void Main(string[] args)
    {
        ThreadPool.QueueUserWorkItem(s => DeleteDir(@"C:\292\Sources\", @"C:\testdel\del.bat"));
    }

    static void DeleteDir(string path, string batchDir)
    {
        var process = new Process
        {
            StartInfo =
            {
                Arguments = string.Format("{0}",
                                          path)
            }
        };

        process.StartInfo.FileName = batchDir;
        process.Start();
    }
}

Here is the contents of the batch file:

del %1 /f /s /Q

I've also tried with Directory.Delete etc.

TFSBuild executes the task and then stops the build, but the delete task does not complete. If I don't call it async, then it just kills the delete task after ~1 min.

How do I get this delete task to execute after the parent process is killed?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pierre
  • 330
  • 1
  • 3
  • 20

1 Answers1

1

The trick is to start another process to do the delete. Powershell is my sidekick for doing this.

I have a utility script called Spawn-Cmd.ps1 which creates a batch file for me and kicks it off. Note it could also kick off an exe or another powershell process, but I use batch file.

param([string]$cmdToSpawn)

$temp = [IO.Path]::GetTempFileName() + '.cmd'

Out-File -FilePath $temp -InputObject $cmdToSpawn -Encoding ASCII

Start-Process -FilePath $temp -WindowStyle Hidden

Next modify your tfs build script to call the script. Here is a sample msbuild file.

<?xml version="1.0" encoding="utf-8"?>
<Project  DefaultTargets="SpawnDelete" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

    <Target Name="SpawnDelete">
        <PropertyGroup>
            <Cmd>rd /s /q \"z:\path\to\folder\"</Cmd>
        </PropertyGroup>

        <Exec Command="powershell -file Spawn-Cmd.ps1 &quot;$(Cmd)&quot;" />
    </Target>
</Project>

The command will run to completion regardless of what happens to tfsbuild process.

Note some other options for achieving this are in this post: MSBuild exec task without blocking

Community
  • 1
  • 1
Avner
  • 4,286
  • 2
  • 35
  • 42
  • Decided to go with a service that deletes completed build folders once a day (due to simplicity and my lack of powershell knowledge). But it looks like your answer could very well work, so I'm marking it as answer :) Thanks – Pierre Aug 24 '15 at 13:23
  • Cheers! Also I'm glad to hear you have a solution. – Avner Aug 24 '15 at 14:20