首页 > 解决方案 > 如何使用powershell删除具有特定名称的所有文件夹

问题描述

我有一个文件夹,我必须从中删除所有名称如“tempspecssuite_”的子文件夹

我的文件夹结构如下

  1. 文件夹 1
    • 源代码
    • 目标
    • tempspecssuite_0
    • tempspecssuite_1

我想递归删除名称为 tempspecssuite_ 的文件夹

我尝试使用以下命令,但没有成功

Get-Childitem -path C:\folder1 -Recurse | where-object {$_.Name -ilike "*tempspecssuite_*"} | Remove-Item -Force -WhatIf

标签: powershell

解决方案


管道对象需要用$_, not来引用$,如下图:

Get-Childitem -Path C:\folder1 -Recurse | Where-Object {$_.Name -ilike "*tempspecssuite*"} | Remove-Item -Force -WhatIf

也可以使用common 参数引用$PSItem或设置为自定义变量。您可以在和中-PipelineVariable了解更多信息。about_pipelinesabout_objectsabout_automatic_variables

您还可以通过使用-Filter参数 from来简化上述操作,该参数Get-ChildItem也接受通配符:

Get-ChildItem -Path C:\folder1 -Directory -Filter tempspecssuite_* -Recurse | Remove-Item -Force -Recurse -WhatIf

这允许Get-ChildItem在检索文件时过滤文件,而不是Where-Object事后过滤。

您还可以使用-Directory开关限制过滤,因为我们只关心删除目录。


推荐阅读