2

我有一个目录内每个构建生成的文件列表C:\BuildArtifacts

目录的内容如下所示:

TestBuild-1.0.0.1.zip
TestBuild-1.0.0.2.zip
TestBuild-1.0.0.3.zip
TestBuild-1.0.0.4.zip
TestBuild-1.0.0.5.zip
TestBuild-1.0.0.6.zip

现在,对于每个增量构建,我只想保留两个最近的工件并删除其余的。所以,在这个例子中,我想保留TestBuild-1.0.0.5.zipTestBuild-1.0.0.6.zip

我怎样才能用 MSBuild 做到这一点?

笔记:

我设法在一个项目中获取上述列表

 <Exec WorkingDirectory="$(Artifacts)\.." Command="dir /B /A:-D /O:-N" Outputs="ArchiveFileList" />
4

2 回答 2

7

好吧,我们编写了一个自定义任务来按文件名对文件进行排序,然后将要删除的文件列表(不包括列表中的前两个)输出到一个Item

自定义任务:

 <UsingTask
    TaskName="Cleanup"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
    <ParameterGroup>
      <TargetPath ParameterType="System.String" Required="true"/>
      <BackupLength ParameterType="System.Int32" Required="true"/>
      <FilesToExclude ParameterType="System.String[]" Output="true" />
      <FilesToDelete ParameterType="System.String[]" Output="true" />
    </ParameterGroup>
    <Task>
      <Using Namespace="System.IO" />
      <Using Namespace="System.Linq" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
        var diInfo = new DirectoryInfo(TargetPath);
            if (diInfo.Exists)
            {
                var fiInfo = diInfo.GetFiles().OrderByDescending(file => file.Name);

                FilesToExclude = fiInfo.Take(BackupLength).Select(file => file.FullName).ToArray();
                FilesToDelete = fiInfo.Skip(BackupLength).Select(file => file.FullName).ToArray();
            }
        ]]>
      </Code>
    </Task>
  </UsingTask>

用法

<!-- Clean old archives. Keep the recent two and deletes rest. -->
<Cleanup TargetPath="$(PackageRoot)" BackupLength="2">
  <Output TaskParameter="FilesToDelete" ItemName="FilesToClean" />
</Cleanup>

<Message Text="Cleaning Old Archives" Importance="High" />
<Delete Files="@(FilesToClean)" />
于 2012-06-05T06:26:02.140 回答
2

请测试此命令,然后<exec ...>使用del而不是echo

for /f %x in ('cmd /c "dir /B /A-D /O-N | more +2"') do echo %x
于 2012-06-01T04:16:59.627 回答