【问题标题】:Remove empty directories using msbuild使用 msbuild 删除空目录
【发布时间】:2012-06-16 06:08:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: msbuild


    【解决方案1】:

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

    <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>
    

    【讨论】:

    • 我不认为这是正确的。不得删除包含包含文件的目录的目录。请参阅 OP 第一行中有关递归等的确切文本。
    • 包含文件的目录不会被删除,因为带有 AllDirectories 选项的目录的文件计数不会为 0。
    • 啊,我没注意AllDirectories 部分。对于在树深处包含大量文件的深度嵌套树来说效率有些低,但我怀疑这在实践中通常会成为一个问题。不过,我觉得它相当优雅。谢谢!
    【解决方案2】:

    使用运行 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

    【讨论】:

    • 并不是我真正想要的(依赖于 msbuild 文件之外的文件),但谢谢。可能有一天会派上用场,因为我有时也使用 PowerShell。
    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2013-08-05
    • 2021-08-27
    • 2012-05-31
    • 2016-10-16
    • 2020-09-19
    • 2023-03-11
    相关资源
    最近更新 更多