【问题标题】:Recursively Delete Files and Directories Using a Filter on the Directory Name使用目录名称上的过滤器递归删除文件和目录
【发布时间】:2017-05-20 12:18:52
【问题描述】:

我正在尝试根据指定所需目录/子目录名称的过滤器删除所有目录、子目录和其中包含的文件。

例如,如果我有 c:\Test\A\B.doc、c:\Test\B\A\C.doc 和 c:\Test\B\A.doc 并且我的过滤器指定了所有目录命名为“A”,我希望剩余的文件夹和文件分别是 c:\Test、c:\Test\B 和 c:\Test\B\A.doc。

我正在尝试在 PowerShell 中执行此操作,但对它不熟悉。

以下 2 个示例将删除与我指定的过滤器匹配的所有文件,但同时也删除与过滤器匹配的文件。

$source = "C:\Powershell_Test" #location of directory to search
$strings = @("A")
cd ($source);
Get-ChildItem -Include ($strings) -Recurse -Force | Remove-Item -Force –Recurse

Remove-Item -Path C:\Powershell_Test -Filter A

【问题讨论】:

    标签: powershell recursion directory


    【解决方案1】:

    我认为你不能那么简单地做到这一点。这将获取目录列表,并将路径分解为其组成部分,并验证过滤器是否与这些部分之一匹配。如果是这样,它会删除整个路径。

    如果它因为嵌套(test-path)而删除了一个目录,它会增加一点小心处理,并且 -Confirm 有助于确保如果这里有错误,你有机会验证行为。

    $source = "C:\Powershell_Test" #location of directory to search
    $filter = "A"
    Get-Childitem -Directory -Recurse $source | 
        Where-Object { $_.FullName.Split([IO.Path]::DirectorySeparatorChar).Contains($filter) } |
        ForEach-Object { $_.FullName; if (Test-Path $_) { Remove-Item $_ -Recurse -Force -Confirm } }
    

    【讨论】:

    • 您的过滤器是一个数组,但您的问题并不清楚您是否打算在该数组中包含多个项目。如果是这样,将 Contains 更改为遍历数组中的选项的内容相对简单。
    【解决方案2】:

    我会使用这样的东西:

    $source = 'C:\root\folder'
    $names  = @('A')
    
    Get-ChildItem $source -Recurse -Force |
      Where-Object { $_.PSIsContainer -and $names -contains $_.Name } |
      Sort-Object FullName -Descending |
      Remove-Item -Recurse -Force
    

    Where-Object 子句将来自Get-ChildItem 的输出限制为仅名称存在于数组$names 中的文件夹。其余项目按其全名降序排序可确保子文件夹在其父文件夹之前被删除。这样可以避免在尝试删除已被先前的递归删除操作删除的文件夹时出错。

    如果您有 PowerShell v3 或更新版本,您可以直接使用 Get-ChildItem 进行所有过滤:

    Get-ChildItem $source -Directory -Include $names -Recurse -Force |
      Sort-Object FullName -Descending |
      Remove-Item -Recurse -Force
    

    【讨论】:

    • 这看起来很有希望 - 我今天必须尝试一下并学习一些新东西。 :)
    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 2013-06-07
    • 2014-05-12
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多