1

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()}
2

1 Answer 1

1

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.

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

Comments

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.