Categories
directory powershell

How to quietly remove a directory with content in PowerShell

328

Using PowerShell, is it possible to remove some directory that contains files without prompting to confirm action?

1

475

Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

or, with shorter version

rm /path -r -force

6

  • 25

    I’ve found that I need to run this twice when run on a directory that contains subdirectories. The first time, there will be a lot of “The directory is not empty” errors. The second time, it completes with no errors.

    Dec 2, 2011 at 20:02

  • 3

    If I want delete only contents of folder but not delete folder?

    – Kiquenet

    Mar 13, 2013 at 8:26

  • 3

    @Kiquenet- This works for me, if I add a trailing slash to the path, so this example becomes Remove-Item .\foldertodelete* -Force -Recurse

    Aug 19, 2013 at 21:11


  • 4

    If you want it to ignore a missing folder you can add -ErrorAction Ignore, although that will also hide other errors.

    May 13, 2016 at 14:00

  • 3

    @Kiquenet Then you can use wildcards to remove everything within that folder: Remove-Item './folder/*'. If you really want to clear out only files of all folders you can list all leafs and pipe it to the Remove-Item cmdlet Get-ChildItem -Recurse -File | Remove-Item

    Jun 1, 2019 at 11:32


77

From PowerShell remove force answer:
help Remove-Item says:

The Recurse parameter in this cmdlet does not work properly

The command to workaround is

Get-ChildItem -Path $Destination -Recurse | Remove-Item -force -recurse

And then delete the folder itself

Remove-Item $Destination -Force 

7

  • 1

    If I want delete only contents of folder but not delete folder?

    – Kiquenet

    Mar 13, 2013 at 8:26

  • 3

    @beppe9000: I believe, yes. In the recent scripts I am using Remove-Item -Recurse -Force $dir and it works.

    Apr 4, 2016 at 10:56


  • Ok, but I just read that the problem is still here on the windows 10 extended Get-Help Remove-Item documentation obtained after Update-Help is run…

    – beppe9000

    Apr 4, 2016 at 17:55

  • 2

    Get-ChildItem should also have the -Force argument, so that it also returns hidden files/folders.

    Apr 22, 2016 at 9:20

  • 1

    I have modularized this answer into a function — see here

    – sam-6174

    Jun 3, 2021 at 18:28

61

This worked for me:

Remove-Item $folderPath -Force  -Recurse -ErrorAction SilentlyContinue

Thus the folder is removed with all files in there and it is not producing error if folder path doesn’t exists.

2

  • 3

    This does not delete the folder.

    – variable

    Jun 3, 2020 at 5:23

  • 2

    @variable, it deleted the folder when I tried.

    Feb 2 at 9:21