Remove multiple specific named folders and ther subfolders with files with Powershell
Matthew Harrington
Because I am new to powershell, I have the following situation.
I have a path d:\folder with a lot of subfolder with subfolders en files. In this folder structure, I want to remove all folders with the name 'Temp', 'History', 'Thumbnails' and all the folders en files under that specific folder name.
I have used the following code sofar $path = "d:\folder\" Get-ChildItem $path -Recurse -Force -Directory | Where-Object {$_.Name -eq 'temp'} | % {Remove-Item $_.FullName}
This is only for 1 folder. I can't find the way for multiple folders? And with this code I am getting een popup asking the delete the folder. Is there a way to do this silence?
1 Answer
Try with the -Include parameter on Get-ChildItem, which can take an array of names to 'filter' on. That way you don't need the Where-Object clause.
Also, there is no need for the ForEach-Object loop (alias %), because Remove-Item can work on the piped results straight away:
$path = 'd:\folder'
Get-ChildItem $path -Recurse -Force -Directory -Include 'Temp', 'History', 'Thumbnails' |
Remove-Item -Recurse -Confirm:$false -Force -WhatIfBy adding the -Recurse switch to Remove-Item, there will be no popup when a folder has child items in it.
I have added safety switch -WhatIf so the folders will not actually be removed. You will only see in the console what would happen.
Once you're happy with that, remove the -WhatIf switch to start deleting