18

I'm trying to delete all files (but not directories) in D:\MyTemp folder, I've tried:

Remove-Item "D:\MyTemp"
Remove-Item "D:\MyTemp\*"

However, when I check, all the files are still there.
What am I missing?

SteB
  • 1,009
  • 6
  • 16
  • 31

5 Answers5

20

Try this:

Get-ChildItem *.* -recurse | Where { ! $_.PSIsContainer }

Found it here: https://superuser.com/questions/150748/have-powershell-get-childitem-return-files-only

To delete all files in the specified directory only (ignoring sub-dirs):

Remove-Item "D:\MyTemp\*.*" | Where { ! $_.PSIsContainer }
bourne
  • 314
  • 1
    This only lists file in the current directory – SteB Nov 02 '12 at 12:15
  • My bad, wasn't sure if you wanted to do recurse. I'll edit the original. You can just add -recurse to the Get-ChildItem command – bourne Nov 02 '12 at 12:17
  • This works (only delete files from specified directory, ignoring sub-dirs): Remove-Item "D:\MyTemp\." | Where { ! $_.PSIsContainer } – SteB Nov 02 '12 at 12:22
  • That's great. Glad you got it working. – bourne Nov 02 '12 at 12:42
  • Sorry btw SteB, I just noticed I forgot to include the Remove-Item. It's going to be a long day wow! – bourne Nov 02 '12 at 12:50
  • NB: running update-help then help remove-item -examples you'll see that remove-item's -recurse parameter is faulty; hence the need to use get-childitem to take advantage of that parameter. – JohnLBevan Nov 07 '14 at 18:27
16

The accepted answer didn't work for me, instead I needed:

Get-Childitem -File | Foreach-Object {Remove-Item $_.FullName}

To include folders as well as files, add -Recurse:

Get-Childitem -File -Recurse | Foreach-Object {Remove-Item $_.FullName}
79E09796
  • 264
  • 2
  • 6
4

You were nearly there, you just needed:

Remove-Item "D:\MyTemp\*.*"
1

The simplest way I'm aware of would be the following (obviously navigate to the directory you want to empty files from):

Get-ChildItem -File -Recurse | Remove-Item

I'm not sure if this requires a minimum version but I'm pretty sure this has worked for a long time.

Zac
  • 111
1

@bourne almost had it:

Get-ChildItem *.* -recurse | Where { ! $_.PSIsContainer } | remove-item
Mordechai
  • 111