Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

How to delete all folders with a specific name using powershell

I have got a folder from where I have to delete all the subfolders having name like "tempspecssuite_"

My folder structure is like below

  1. Folder1
    • src
    • target
    • tempspecssuite_0
    • tempspecssuite_1

I want recursively delete the folders with name like tempspecssuite_

I tried using below command but it didn't work

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pipeline objects need to be referenced with $_, not $, as shown below:

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

Which can also be referenced with $PSItem or set to a custom variable with the -PipelineVariable common parameter. You can find out more in about_pipelines,about_objects and about_automatic_variables.

You could also simplify the above by making use of the -Filter parameter from Get-ChildItem, which also accepts wildcards:

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

Which allows Get-ChildItem to filter files while they are getting retrieved, rather than filtering with Where-Object afterwards.

You can also limit the filtering with the -Directory switch, since we only care about deleting directories.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...