如何递归处理路径,以便在处理完成后,路径下没有空目录。
例如,假设我们有C:\Dir1\Dir2\Dir3
并且这些目录中没有任何文件。结果应该是删除所有三个目录。
我想在不使用自定义任务的情况下完成此任务。
答案 0 :(得分:12)
像这样的东西应该可以工作,虽然只是为了获得数组长度,但没有检查计算数千个文件的性能......
<Project DefaultTargets="Foo" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Foo">
<ItemGroup>
<Directories Include="$([System.IO.Directory]::GetDirectories('D:\foo', '*', System.IO.SearchOption.AllDirectories))" />
<Directories>
<Files>$([System.IO.Directory]::GetFiles("%(Directories.Identity)", "*", System.IO.SearchOption.AllDirectories).get_Length())</Files>
</Directories>
</ItemGroup>
<RemoveDir Directories="@(Directories)" Condition="%(Files)=='0'" />
</Target>
</Project>
答案 1 :(得分:4)
使用运行PowerShell的Exec
任务:
<强>的MSBuild 强>
<Project DefaultTargets="DefaultTarget" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<CleanPath>C:\MyDirAboveDir1</CleanPath>
</PropertyGroup>
<Target Name="DefaultTarget">
<Exec Command="PowerShell .\RemoveDir.ps1 '$(CleanPath)'" />
</Target>
</Project>
PowerShell RemoveDir.ps1
Param ([string]$folderpath = $(throw "provide folderpath"))
$folders = Get-ChildItem $folderpath -recurse -force | ? {$_.PSIsContainer}
if ($folders -ne $null)
{
[array]::Reverse($folders)
foreach($folder in $folders)
{
Write-Host "Examining contents of $($folder.fullname)"
$childitems = Get-Childitem $folder.fullname -recurse -force | ? { $_.PSIsContainer -eq $false }
if($childitems -eq $null)
{
"Remove folder: " + $folder.FullName
Remove-Item $folder.FullName -Recurse -Force
}
else
{
Write-host "Files found in $folder, skipping delete"
}
$childitems = $null
}
}
else
{
Write-Host "no sub folders found"
}
礼貌Guy Ellis Rocks: Powershell script to remove empty directories