7

如何递归处理路径,以便处理完成后路径下没有空目录。

例如,假设我们有C:\Dir1\Dir2\Dir3并且这些目录中没有文件。结果应该是删除所有三个目录。

我想在不使用自定义任务的情况下完成此操作。

4

2 回答 2

14

像这样的东西应该可以工作,虽然只是为了获得数组长度,但没有检查计算数千个文件的性能......

<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>
于 2012-06-15T17:32:58.460 回答
4

使用Exec运行 PowerShell 的任务:

微软构建

<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 删除目录.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 脚本

于 2012-06-15T14:13:50.997 回答