根据修改的时间从目录MsBuild-删除文件/名称(MsBuild- Delete files fr

2019-09-17 16:02发布

我对每个生成的文件列表建立的目录里面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" />

Answer 1:

好了,我们写了一个自定义任务的文件通过他们的名字和排序,然后输出的文件列表中删除(不包括在列表中的前两个)到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)" />


Answer 2:

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

for /f %x in ('cmd /c "dir /B /A-D /O-N | more +2"') do echo %x


文章来源: MsBuild- Delete files from a directory based on time modified / name