498

What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7.

I have learned from several sources that the most obvious command, Remove-Item $targetDir -Recurse -Force, does not work correctly. This includes a statement in the PowerShell V2 online help (found using Get-Help Remove-Item -Examples) that states:

...Because the Recurse parameter in this cmdlet is faulty, the command uses the Get-Childitem cmdlet to get the desired files, and it uses the pipeline operator to pass them to the Remove-Item cmdlet...

I have seen various examples that use Get-ChildItem and pipe it to Remove-Item, but the examples usually remove some set of files based on a filter, not the entire directory.

I am looking for the cleanest way to blow out an entire directory, files and child directories, without generating any user warning messages using the least amount of code. A one-liner would be nice if it is easy to understand.

7
  • 2
    powershell, i know, but RD /S /Q Commented Nov 17, 2009 at 23:49
  • 2
    "RD /S /Q" doesn't seem to work in PowerShell -- says "Remove-Item : A positional parameter cannot be found that accepts argument '/q'." Commented Sep 7, 2012 at 19:27
  • 8
    rd is an alias for Remove-Item in powershell. cmd /c "rd /s /q" works, though. Commented May 2, 2013 at 2:45
  • 5
    I cant believe powershell breaks basic functionality like this by hiding perfectly functional msdos commands! you can use rmdir or rd in cmd but they are both hijacked in powershell Commented Feb 10, 2014 at 13:14
  • 1
    There is also this: stackoverflow.com/a/53561052/284111 Commented Mar 13, 2020 at 4:20

23 Answers 23

851
Remove-Item -Recurse -Force some_directory

does indeed work as advertised here.

rm -r -fo some_directory

are shorthand aliases that work too.

As far as I understood it, the -Recurse parameter just doesn't work correctly when you try deleting a filtered set of files recursively. For killing a single directory and everything below it seems to work fine.

Sign up to request clarification or add additional context in comments.

15 Comments

I think you are correct. I was getting a "Cannot remove the item at 'some directory' because it is in use." error and assumed it was an issue with the recursion algorithm and went searching for a workaround. It turns out I had a process I fired off earlier in the script that was working in the target directory. When changed the script to wait for the other process the "Remove-Item -Recurse -Force" command works. Always look in the mirror first:)
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.
Kristopher Johnson, I get similar errors with varying tools on Windows 7. It seems that the delete call returns earlier than a file or folder is actually removed, causing trouble sometimes. This seems to happen in Explorer, Far, cmd and PowerShell.
@Joey "It seems that the delete call returns earlier than a file or folder is actually removed, causing trouble sometimes." --> For clarification: the parent folder will not be deleted and one gets the following error: "[parent folder] cannot be removed because it is not empty." I see this happen constantly on (slow) networked drives. The only solution is the old one: cmd /c rd as stated below.
What's about "The directory is not empty" errors ?serverfault.com/questions/199921/powershell-remove-force Maybe better get-childitem * -include *.csv -recurse | remove-item I don't know. See stackoverflow.com/a/1668471/206730
|
47

I used:

rm -r folderToDelete

This works for me like a charm (I stole it from Ubuntu).

6 Comments

Doesn't that require cygwin, git, or some other tool that can simulate a bash shell on Windows?
@Pete, no, it does not require anything but PowerShell. rm is an alias for Remove-Item in PowerShell's default configuration. Check the output of Get-Alias rm for more details. The -r is taking advantage of PowerShell's partial matching behavior on parameters. Since Remove-Item only has the one parameter that starts with an 'r', -Recurse, -r matches that. Thus, the following all will work the same: rm -r, rm -re, Remove-Item -Recurse. (Note that neither rm -rf nor rm -r -f will work, but rm -r -fo will. -rf matches no parameters and -f matches more than one.)
How about that. The Powershell rm alias for "Remove-Item -Recurse -Force some_dir" works better than directly using remove-item. I received the same errors "Cannot remove the item at 'some directory' . I switch from remove-item to rm -r with no errors!?
Perhaps it's because I use the -R instead of -r (though as far as I know PowerShell is like the rest of Windows not case-sensitive hence it should't make a difference) but I got an error that the folders I'm trying to delete are not empty.
It does not work on PowerShell 5.1, I had to use rm -r -fo (rm -r -f does not work either since the -f parameter is ambiguous as it can match both -Force and -Filter).
|
35

When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.

This answer attempts to prevent that error by individually deleting the files.

function Get-Tree($Path, $Include='*') {
    @(Get-Item $Path -Include $Include -Force) +
        (Get-ChildItem $Path -Recurse -Include $Include -Force) |
        Sort-Object pspath -Descending -unique
}

function Remove-Tree($Path, $Include='*') {
    Get-Tree $Path $Include | Remove-Item -force -recurse
}

Remove-Tree some_directory

An important detail is the sorting of all the items with pspath -Descending so that the leaves are deleted before the roots. The sorting is done on the pspath parameter since that has more chance of working for providers other than the file system. The -Include parameter is just a convenience if you want to filter the items to delete.

It's split into two functions since I find it useful to see what I'm about to delete by running

Get-Tree some_directory | Select-Object fullname

6 Comments

While resolving an issue using PowerShell in TFS build scripts, this proved to be the correct answer.
This is the solution for me as well. Have yourself some points my good man!
Worked for me. I couldn't get recursive deletion of contents of a folder, but your solution worked for me. thanks
This is a very robust solution
I'm not sure why the accepted answer has so many votes - I personally still get intermittent errors using remove-item -recurse in Powershell v5 so this solution is best for me.
|
17
rm -r ./folder -Force

...worked for me

Comments

17

If you're committed to PowerShell, you can use this, as explained in the accepted answer:

rm -r -fo targetDirectory

But I've found it to be faster to use the Windows command prompt:

rmdir /s/q targetDirectory

In addition to being faster, another advantage to using the command prompt option is that it starts deleting files immediately (PowerShell does some enumeration first), so if something breaks while it's running, you've at least made some progress in deleting files.

1 Comment

rmdir has the added benefit of successfully deleting read-only files (like in a .git folder) -- In older powershell versions, (get-item targetDir).Delete($true) will fail to delete git repos.
14

Try this example. If the directory does not exist, no error is raised. You may need PowerShell v3.0.

remove-item -path "c:\Test Temp\Test Folder" -Force -Recurse -ErrorAction SilentlyContinue

Comments

11

Use the old school DOS command rd:

rd /s <directory>

1 Comment

If this is part of a script, you'd have to use /q (Quiet mode, do not ask if ok to remove a directory tree with /S) too.
9

To avoid the "The directory is not empty" errors of the accepted answer, simply use the good old DOS command as suggested before. The full PowerShell syntax ready for copy-pasting is:

& cmd.exe /c rd /S /Q $folderToDelete

2 Comments

It still gives "The directory is not empty" error for folders!?
I wanted to delete an Android Studio project and this is workded after i closed the Android Studio!
8

For some reason, John Rees' answer sometimes did not work in my case. But it led me in the following direction.

First I try to delete the directory recursively with the buggy -recurse option. Afterwards, I descend into every subdirectory that's left and delete all files.

function Remove-Tree($Path)
{
    Remove-Item $Path -force -Recurse -ErrorAction silentlycontinue

    if (Test-Path "$Path\" -ErrorAction silentlycontinue)
    {
        $folders = Get-ChildItem -Path $Path –Directory -Force
        ForEach ($folder in $folders)
        {
            Remove-Tree $folder.FullName
        }

        $files = Get-ChildItem -Path $Path -File -Force

        ForEach ($file in $files)
        {
            Remove-Item $file.FullName -force
        }

        if (Test-Path "$Path\" -ErrorAction silentlycontinue)
        {
            Remove-Item $Path -force
        }
    }
}

2 Comments

Can you reproduce the error when running my functions? I'd like to know so that I can improve them.
Sorry, don't remember the exact setting. :/ I think it was when multiple sub-directories where involved. It happened that the call to "Remove-Item -force -recurse" did not delete all files and in that case the last Remove-Tree failed because the directory was not empty. That's why I came up with the new solution to first try the buggy built-in version (-force) and then manually descending into each directory and deleting "manually" what's left. This version is in use regularly and up till now it is working. The only cause it failed was when a program still holds a handle to a directory.
5

Use:

del <directory> -Recurse -Force # I prefer this, short and sweet

Or:

Remove-Item <directory> -Recurse -Force

If you have a huge directory then I usually do:

while (dir | Where-Object name -match <directory>) {Write-Host Deleting; sleep -s 3}

Run this in another PowerShell terminal, and it will stop when it is done.

2 Comments

I admit your idea with the monitoring can be useful, but it is barely different from just printing a message once it is finished, and in case there was any problem stopping the Remove-Item, your loop will never end.
@RaúlSalinas-Monteagudo true but it is definitely for prod or unattended use case scenario. It has to be small enough for someone to just remember and type on the go and not to run a sophisticated .ps1 file to just a directory.
4

Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors. Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors. I do not know why this happens, though some insight may be gained from this Stack Overflow posting.

I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays. The following runs well for me:

# First remove any files in the folder tree
Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force

# Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }

# Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
Remove-Item -LiteralPath $FolderToDelete -Recurse -Force

# Finally, give Windows some time to finish deleting the folder (try not to hurl)
Start-Sleep -Seconds 4

A Microsoft TechNet article, Using Calculated Properties, in PowerShell was helpful to me in getting a list of subfolders sorted by depth.

Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (i.e., using ping as shown below).

DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
RD /S /Q "C:\Some\Folder\to\Delete" > nul
if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul

1 Comment

See this answer, which David Faivre mentioned in his answer below, for an explanation of why directory deletion sometimes fails, and a more sophisticated remedy.
4

There seems to be issues where Remove-Item -Force -Recurse can intermittently fail on Windows because the underlying file system is asynchronous. This answer seems to address it. The user has also been actively involved with the PowerShell team on GitHub.

Comments

3

Add a custom function in your PowerShell $profile:

function rmrf([string]$Path) {
    try {
        Remove-Item -Recurse -ErrorAction:Stop $Path
    } catch [System.Management.Automation.ItemNotFoundException] {
        # Ignore
        $Error.Clear()
    }
}

This is the most accurate representation of rm -rf behavior.

Comments

3

While rm -r yields good results, the following method is faster:

$fso = New-Object -ComObject scripting.filesystemobject
$fso.DeleteFolder("D:\folder_to_remove")

To test this, you can easily create a folder with X files (I used: Disk Tools to quickly generate the files).

And then run each of the variants using:

Measure-Command {rm D:\FOLDER_TO_DELETE -r}
Measure-Command {Remove-Item -Path D:\FOLDER_TO_DELETE -Recurse -Force}
Measure-Command {rd -r FOLDER_TO_DELETE }
$fso.DeleteFolder("D:\folder_to_remove")
Measure-Command {$fso.DeleteFolder("D:\FOLDER_TO_DELETE")}

The results on my test folder were:

Remove-Item - TotalMilliseconds : 1438.708
rm - TotalMilliseconds : 1268.8473
rd - TotalMilliseconds : 739.5385
FSO - TotalMilliseconds : 676.8091

The results vary but on my system the winner was the fileSystemObject. I recommend testing this on the target file system to see which method is the best for you.

Comments

2

Another useful trick:

If you find a lot of files with same or similar name convention (like a Mac file with dot prefix name... that famous file pollution), you can easily remove them with one single line from a PowerShell window like this:

ls -r .* | rm

This line is going to remove all files with a dot in the beginning of the name inside the current directory, and all files with same circumstances inside other folders inside this directory too. Be aware about it when using it. :D

3 Comments

Why not use rm -rf .* ? I don`t have powershell to test, but I think it will work.
Its easy; if you just remove the "| rm" from the command, you can view a whole panorama of what you are going to delete, after you were sure, you can complete the command.
Por cierto, para quitar los archivos que empiecen con punto, (como los de mac) pero que tengan propiedad de oculto, puedes usar: ls -r -h .* | rm
2

I took another approach inspired by John Rees, especially when his approach started to fail for me at some point. Basically, recurse the subtree, and sort files by their path-length, and delete from longest to the shortest:

Get-ChildItem $tfsLocalPath -Recurse |  # Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  # Calculate the length of their path
    Sort-Object PathLength -Descending | # Sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } |
    Remove-Item -Force

Regarding the -LiteralPath magic, here's another gotcha that may be hitting you: PowerShell bug in copy/move/rename when filename contains [square bracket characters]

Comments

2

To delete the complete contents, including the folder structure, use:

Get-ChildItem $dest -recurse | ForEach-Object ($_) {Remove-Item $_.fullname -recurse}

The -recurse added to Remove-Item ensures interactive prompts are disabled.

Comments

0

Really simple:

remove-item -path <type in file or directory name>, press Enter

1 Comment

You should offer an example execution too.
0

This is based on @John Rees's answer with some improvements.

Initial files tree . /f

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
│   X-Update-PowerShellCoreFxs.ps1
│   z
│   Z-Config.json
│   Z-CoreFxs.ps1
│
├───HappyBirthday Unicorn
│       collection-of-unicorns-and-hearts-with-rainbows.zip
│       hand-drawing-rainbow-design.zip
│       hand-drawn-unicorn-birthday-invitation-template (2).zip
│       hontana.zip
│       Unicorn - Original.pdf
│       Unicorn-free-printable-cake-toppers.png
│       Unicorn.pdf
│       Unicorn.png
│       Unicorn2.pdf
│       Unicorn3.pdf
│       Unicorn4.pdf
│       Unicorn5.pdf
│       UnicornMLP.pdf
│
├───x
└───y

Code

function Get-ItemTree() {
    param (
        [Parameter()]
        [System.String]
        $Path = ".",

        [Parameter()]
        [System.String]
        $Include = "*",

        [Parameter()]
        [switch]
        $IncludePath,

        [Parameter()]
        [switch]
        $Force

    )
    $result = @()
    if (!(Test-Path $Path)) {
        throw "Invalid path. The path `"$Path`" doesn't exist." #Test if path is valid.
    }
    if (Test-Path $Path -PathType Container)
    {
        $result += (Get-ChildItem "$Path" -Include "$Include" -Force:$Force -Recurse) # Add all items inside of a container, if path is a container.
    }
    if($IncludePath.IsPresent)
    {
        $result += @(Get-Item $Path -Force) # Add the $Path in the result.
    }
    $result = ,@($result | Sort-Object -Descending -Unique -Property "PSPath") # Sort elements by PSPath property, order in descending, remove duplicates with unique.
    return  $result
}

function Remove-ItemTree {
    param (
        [Parameter()]
        [System.String]
        $Path,

        [Parameter()]
        [switch]
        $ForceDebug
    )
    (Get-ItemTree -Path $Path -Force -IncludePath) | ForEach-Object{
        Remove-Item "$($_.PSPath)" -Force
        if($PSBoundParameters.Debug.IsPresent)
        {
            Write-Debug -Message "Deleted: $($_.PSPath)" -Debug:$ForceDebug
        }
    }
}

Write-Host "███ Test 1"
$a = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$true # Tree of a file path. 1 element the file (IncludePath parameter = $true)
$a | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 2"
$b = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$false # Tree of a file path. No Result (IncludePath parameter = $false)
$b | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 3"
$c = Get-ItemTree "." -Force -Include "*" -IncludePath:$true # Tree of a container path. All elements of tree and the container included (IncludePath parameter = $true).
$c | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 4"
$d = Get-ItemTree "." -Force -Include "*" -IncludePath:$false # All elements of tree, except the container (IncludePath parameter = $false).
$d | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Remove-ItemTree -Path "./HappyBirthday Unicorn" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./x" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./y" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./z" -Debug -ForceDebug #Remove file. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.

Get-ChildItem -Force

Output

███ Test 1
"Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json"

███ Test 2

███ Test 3
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx"
]

███ Test 4
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn"
]

DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\UnicornMLP.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn5.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn4.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn3.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn2.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn-free-printable-cake-toppers.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn - Original.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hontana.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawn-unicorn-birthday-invitation-template (2).zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawing-rainbow-design.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\collection-of-unicorns-and-hearts-with-rainbows.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\x
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\y
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\z


    Directory: C:\Users\Megam\OneDrive\Escritorio\pwshcfx

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---           17/5/2021     1:57            272 X-Update-PowerShellCoreFxs.ps1
la---           14/5/2021    18:51            252 Z-Config.json
la---           17/5/2021     4:04          30931 Z-CoreFxs.ps1

tree . /f

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
    X-Update-PowerShellCoreFxs.ps1
    Z-Config.json
    Z-CoreFxs.ps1

No subfolders exist

Comments

0

Please try the below PowerShell script. This script will skip to the next file/folder if got stuck with some error like "Remove-Item : The tag present in the reparse point buffer is invalid."

# Get a list of all the folders to be deleted
$foldersToDelete = Get-ChildItem -Directory -Path "C:\Path\To\Folders"

# Delete each folder recursively, skipping to the next file if stuck with an error
foreach ($folder in $foldersToDelete) {
    try {
        Remove-Item -Path $folder.FullName -Recurse -Force
    } catch {
        Write-Host "Failed to delete folder '$folder.FullName': $_"
        continue
    }
}

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?
-1

Use a combination of Robocopy and rmdir:

# Create an empty folder to use as the source
$emptyDir = "C:\empty"
New-Item -ItemType Directory -Path $emptyDir

# Replace the contents of the target folder with the empty folder (effectively deleting all contents)
robocopy $emptyDir "C:\Path\To\Your\Folder" /mir

# Remove the now-empty folder
Remove-Item "C:\Path\To\Your\Folder" -Recurse -Force

# Remove the temporary empty directory created
Remove-Item $emptyDir -Force

1 Comment

Why do you need the robocopy? Remove-Item will delete the folder and its content anyways (especially with -Recurse flag).
-2

Use:

$users = Get-ChildItem \\ServerName\c$\users\ | select -ExpandProperty name

foreach ($user in $users)
{
    Remove-Item -path "\\Servername\c$\Users\$user\AppData\Local\Microsoft\Office365\PowerShell\*" -Force -Recurse
    Write-Warning "$user Cleaned"
}

I wrote the above to clean some logfiles without deleting the parent directory, and this works perfectly!

Comments

-5
rm -r <folder_name>
c:\>rm -r "my photos"

2 Comments

Please explain that further such that others can learn from your answer
This won't work, as it tries to delete directories before they are empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.