Reputation:
I was wondering if anyone knew how to delete a directory if it has a specified file in it? For example, if have this directory:
PS C:\Users\mike> dir
Directory: C:\Users\mike
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 9/17/2009 6:26 PM 6615 pic001.jpg
-a--- 9/19/2009 9:58 AM 7527 notes.txt
-a--- 8/31/2009 5:03 PM 10506 Project.xlsx
I would like to delete .\mike if it has a jpg file in it, and any other directory that has .jpg files. If a directory does not have the file specified it should not be deleted.
So far what I have is this:
get-childitem "C:\Users\mike" -include *.jpg -recurse | Where-Object { $_.mode -like 'd*' } | remove-item
Upvotes: 2
Views: 567
Reputation: 201592
When you use Get-ChildItem with *.jpg you are only going to get files - well unless you have a dir named {something}.jpg. BTW I would use -filter and stay away from the -include parameter. Thar be dragons - see the docs on that parameter.
This should do the trick for you:
Get-ChildItem 'C:\Users\Mike' *.jpg -r | Foreach {$_.Directory} |
Remove-Item -Recurse -Verbose -WhatIf
If typing shorten that using aliases to:
gci 'C:\Users\Mike' *.jpg -r | %{$_.Directory} | ri -r -v -wh
When you are satisfied with the results, remove the -WhatIf to have it really remove the dirs.
Upvotes: 4