views:

158

answers:

1

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
+4  A: 

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.

Keith Hill
Thanks, that's exactly what I needed. Thanks for the tips as well.
+1 for "There be dragons" :-)
Joey
I see you're thoroughly addicted to the stackoverflow crack Keith!
x0n