使用PowerShell,是否可以删除包含文件的目录而不提示确认操作?


当前回答

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

或者,用更短的版本

rm /path -r -force

其他回答

有些多级目录文件夹需要删除两次,这困扰了我很久。这是我的最终代码,它为我工作,并清理得很好,希望它有帮助。

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')
Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

或者,用更短的版本

rm /path -r -force

如果你有你的文件夹作为一个对象,让我们说你在相同的脚本中使用下一个命令创建它:

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

然后你可以像这样在相同的脚本中删除它

$folder.Delete($true)

$true -递归删除的状态

从PowerShell删除强制答案: help Remove-Item说:

这个cmdlet中的递归参数不能正常工作

要解决的命令是

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

然后删除文件夹本身

Remove-Item $Destination -Force 

由于我的目录在C:\users中,我必须以管理员身份运行powershell,

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

这个命令对我很管用。