Delete DIR recursively if file matches? (Powershell)

I was wondering if anyone knows how to delete a directory if there is a specified file in it? For example, if there is 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 there is a jpg file in it, and any other directory with .jpg files. If the specified file does not exist in the directory, it should not be deleted.

So far I have the following:

get-childitem "C:\Users\mike" -include *.jpg -recurse | Where-Object { $_.mode -like 'd*' } | remove-item

      

+2


source to share


1 answer


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 the -filter and stay away from the -include option. Tar - dragons - see docs about this parameter.

This should do the trick for you:

Get-ChildItem 'C:\Users\Mike' *.jpg -r | Foreach {$_.Directory} | 
    Remove-Item -Recurse -Verbose -WhatIf

      



If while typing, reduce the use of aliases with:

gci 'C:\Users\Mike' *.jpg -r | %{$_.Directory} | ri -r -v -wh

      

When you are satisfied with the results, remove -WhatIf so that it will actually delete directories.

+4


source







All Articles