问题
I have a list of files generated on each build inside a directory C:\BuildArtifacts
The Contents of a directory looks like this:
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
Now, with each incremental build, I just want to retain two recent artifacts and delete the rest. So, in this example, I want to retain TestBuild-1.0.0.5.zip
and TestBuild-1.0.0.6.zip
How can I do it with MSBuild?
Note:
I have managed to fetch the above list in an item
<Exec WorkingDirectory="$(Artifacts)\.." Command="dir /B /A:-D /O:-N" Outputs="ArchiveFileList" />
回答1:
Well, we wrote a custom task to sort the files by their name and then output the list of the files to delete (excluding the first two in the list) into an Item
Custom Task:
<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>
Usage:
<!-- 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)" />
回答2:
Please test this command then <exec ...>
it with del
instead of echo
:
for /f %x in ('cmd /c "dir /B /A-D /O-N | more +2"') do echo %x
来源:https://stackoverflow.com/questions/10843967/msbuild-delete-files-from-a-directory-based-on-time-modified-name