3

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
2
  • 1
    You are missing the underscore $.Name should be $_.Name Commented Jan 6, 2021 at 14:56
  • 1
    thanks Itchydon.. there was a typo in my question, but the problem was I didn't remove the Whatif Commented Jan 6, 2021 at 15:12

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks road runner! it is identifying the directories now but it is not deleting the folders. Could there be anything I am missing
@DevX Are you still using -WhatIf? That will only tell you the effect of the command, but not actually delete. Remove this parameter to perform real deletion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.