使用目录名称过滤器递归删除文件和目录

Liz*_*ell 2 directory powershell recursion

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

例如,如果我有 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
Run Code Online (Sandbox Code Playgroud)

Remove-Item -Path C:\Powershell_Test -Filter A
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 5

我会使用这样的东西:

$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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)