Edwin
Edwin

Reputation: 11

Powershell: Delete folder with specific file in it

I am trying to make a script in powershell to delete all folders in C:\Temp which contains a *.sr_processed file.

I already have this but this only deletes the file and not the folder it was in.

Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { $_.Delete()}

Upvotes: 1

Views: 906

Answers (1)

Palle Due
Palle Due

Reputation: 6312

Your are telling it to delete the file. To delete the folder do something like:

Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { Remove-Item –path $_.Directory.Fullname}

If you have multiple .sr_processed files in a folder it might attempt to delete it more than once. And generally deleting a folder you are globbing is bad practice. So a better idea would be to gather up the folders in a list/hash and delete them at the end.

That would look something like:

# declare array
$foldersToDelete = @()
# fill array with folder names
Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { $foldersToDelete += $_.Directory.Fullname}
# sort and make unique
$foldersToDelete = $foldersToDelete | Sort-Object | Get-Unique
# delete folders
$foldersToDelete | Remove-Item –path $_

This is typed from memory, so you might want to adjust it.

Upvotes: 1

Related Questions