如何从树中删除所有隐藏的 .unwanted 目录?

How to remove all hidden .unwanted directories from a tree?

我想使用 .

从目录树中强制删除任何名为 .unwanted 的隐藏目录

我希望有一个足够简单的解决方案,让新手可以轻松理解和学习。我知道命令 Get-ChildItemRemove-Item 但我还不知道如何使用新类型的变量 chain/pipe 它们。

提供的Bash代码可以翻译成下面的代码:

Get-Childitem *unwanted* -Recurse | Remove-Item -Confirm:$false -ErrorAction SilentlyContinue

根据权限,您可能必须在第二个命令中使用 -Force 参数。我还建议在将这些命令用于任何类型的生产环境之前对其进行一些研究和测试。事情会变得危险 :)

我也会留下一篇关于PowerShell Pipelines的好文章here

您可以根据您的要求尝试这样的操作 -

Get-ChildItem -path \PathToYourFolder\ -recurse | where {$_.PSIsContainer -eq $true -and $_.Name -eq ".unwanted"} | Remove-Item

简而言之,PowerShell 管道获取其左侧 cmdlets 的输出,并将其作为输入传递给右侧的 cmdlets

命令 where {$_.PSIsContainer -eq $true 将所有文件系统对象的 PsIsContainer 属性 用于 select 仅文件夹,这些文件夹的值为 True ($true) PsIsContainer 属性.

Get-ChildItem -Force -Recurse -Directory -Filter .unwanted |
  Remove-Item -Force -Recurse -WhatIf

-WhatIf 预览删除;删除它以执行实际删除。

    需要
  • -Force 才能定位隐藏的项目(并且,在 Windows 上的 Remove-Item 的情况下,要覆盖 r (read-only) 属性,如果允许的话)。

  • 需要
  • -Recurse 在整个子树 (Get-ChildItem) 中查找目录,并在没有确认提示的情况下删除非空目录 (Remove-Item)。

顺便说一句:使用 -Filter 是定位感兴趣目录的最有效方法,因为它在源头进行过滤,而(暗示)使用 -Path 会使 PowerShell 枚举首先是所有目录,然后再过滤。