ChatGPT解决这个技术问题 Extra ChatGPT

How to quietly remove a directory with content in PowerShell

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


O
Ohad Schneider
Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

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.
If I want delete only contents of folder but not delete folder?
@Kiquenet- This works for me, if I add a trailing slash to the path, so this example becomes Remove-Item .\foldertodelete* -Force -Recurse
If you want it to ignore a missing folder you can add -ErrorAction Ignore, although that will also hide other errors.
@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
C
Community

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 

If I want delete only contents of folder but not delete folder?
@beppe9000: I believe, yes. In the recent scripts I am using Remove-Item -Recurse -Force $dir and it works.
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...
Get-ChildItem should also have the -Force argument, so that it also returns hidden files/folders.
I have modularized this answer into a function -- see here
n
necrifede

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.


This does not delete the folder.
@variable, it deleted the folder when I tried.
d
divenex

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

One can also clean up a folder, but not the folder itself, using rm -R .\DirName\* (noted by Jeff in the comments).


You can also use rm -R .\DirName\* to clean up the folder without deleting the folder itself
none of the powershell commands nor this one works for me on a 2016 server core computer. They all say, `cannot be removed because it is not empty'. I also tried the rd command in windows. I can move the folder anywhere, just can't delete.
S
Salman

in short, We can use rm -r -fo {folderName} to remove the folder recursively (remove all the files and folders inside) and force


Thanks for using -r and -fo. That way the command is much concise.
still i wonder why powershell not just inherit the whole commands from linux, say rm -rf folder/
E
Eric Pohl

To delete content without a folder you can use the following:

Remove-Item "foldertodelete\*" -Force -Recurse

P
Peter Mortensen

rm -Force -Recurse -Confirm:$false $directory2Delete didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.

I hope this helps. It was driving me bannanas.


Thank you, same goes for me! FInally this folder was deleted when calling from PowerShell CLI and not while developing in PowerShell ISE.
v
variable

This worked for me:

Remove-Item C:\folder_name -Force -Recurse

I
Imtiaz Shakil Siddique

Powershell works with relative folders. The Remove-Item has couple of useful aliases which aligns with unix. Some examples:

rm -R -Force ./directory
del -R -Force ./directory/*

u
user2426679

Below is a copy-pasteable implementation of Michael Freidgeim's answer

function Delete-FolderAndContents {
    # http://stackoverflow.com/a/9012108

    param(
        [Parameter(Mandatory=$true, Position=1)] [string] $folder_path
    )

    process {
        $child_items = ([array] (Get-ChildItem -Path $folder_path -Recurse -Force))
        if ($child_items) {
            $null = $child_items | Remove-Item -Force -Recurse
        }
        $null = Remove-Item $folder_path -Force
    }
}

C
CDspace
$LogPath = "E:\" # Your local of directories
$Folders = Get-Childitem $LogPath -dir -r | Where-Object {$_.name -like "*temp*"}
foreach ($Folder in $Folders) 
{
    $Item =  $Folder.FullName
    Write-Output $Item
    Remove-Item $Item -Force -Recurse
}

On script above i print fullname of folder and remove it. \o/
O
OMKAR AGRAWAL

Since my directory was in C:\users I had to run my powershell as administrator,

del ./[your Folder name] -Force -Recurse

this command worked for me.


Just as a side-note: del is an alias for Remove-Item.
D
Dmitriy Reznikov

If you have your folder as an object, let's say that you created it in the same script using next command:

$folder = New-Item -ItemType Directory -Force -Path "c:\tmp" -Name "myFolder"

Then you can just remove it like this in the same script

$folder.Delete($true)

$true - states for recursive removal


C
Community
$LogPath = "E:\" # Your local of directories
$Folders = Get-Childitem $LogPath -dir -r | Where-Object {$_.name -like "*grav*"} # Your keyword name directories

foreach ($Folder in $Folders) 
{
    $Item =  $Folder.FullName
    Write-Output $Item
    Remove-Item $Item -Force -Recurse -ErrorAction SilentlyContinue
}

On script above i print fullname of folder and remove it. A good job...
Hi Anderson, you should edit answers if you are not planning to add 2 different answers, maybe you want to delete one of them?
S
SwissCodeMen

If you want to concatenate a variable with a fixed path and a string as the dynamic path into a whole path to remove the folder, you may need the following command:

$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse

In the variable $newPath the concatenate path is now: "C:\Users\myUserName\Desktop\Folder\SubFolder"

So you can remove several directories from the starting point ("C:\Users\myUserName\Desktop"), which is already defined and fixed in the variable $fixPath.

$fixPath = "C:\Users\myUserName\Desktop"
Remote-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse

A
Aspirant Zhang

Some multi-level directory folders need to be deleted twice, which has troubled me for a long time. Here is my final code, it works for me, and cleans up nicely, hope it helps.

function ForceDelete {
    [CmdletBinding()]
    param(
        [string] $path
    )
    
    rm -r -fo $path
    
    if (Test-Path -Path $path){
        Start-Sleep -Seconds 1
        Write-Host "Force delete retrying..." -ForegroundColor white -BackgroundColor red
        rm -r -fo $path
    }
}

ForceDelete('.\your-folder-name')
ForceDelete('.\your-file-name.php')

this is just a wrapper around answers already posted. what benefit do you see in your Answer over the others? ///// also, calling a function with () around the values is not correct in PoSh ... that just says "treat this as an array".