使用PowerShell,是否可以删除包含文件的目录而不提示确认操作?
当前回答
2018年更新
在当前版本的PowerShell中(在Windows 10和Windows 11上使用v5.1进行测试,在2023年),可以使用更简单的Unix语法rm -R .\DirName无声地删除目录.\DirName及其可能包含的所有子目录和文件。事实上,许多常见的Unix命令在PowerShell中的工作方式与在Linux命令行中相同。
也可以使用rm -R .\DirName\* (Jeff在评论中提到了)清理文件夹,但不能清理文件夹本身。
其他回答
$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
}
下面是Michael Freidgeim答案的一个可复制粘贴的实现
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
}
}
如果你想把一个固定路径的变量和一个字符串作为动态路径连接到一个完整的路径来删除文件夹,你可能需要下面的命令:
$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
在变量$newPath中,连接路径现在是:"C:\Users\myUserName\Desktop\Folder\SubFolder"
因此,您可以从起点(“C:\Users\myUserName\Desktop”)删除几个目录,该起点已经在变量$fixPath中定义和固定。
$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remove-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remove-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse
从PowerShell删除强制答案: help Remove-Item说:
这个cmdlet中的递归参数不能正常工作
要解决的命令是
Get-ChildItem -Path $Destination -Recurse | Remove-Item -force -recurse
然后删除文件夹本身
Remove-Item $Destination -Force
rm -Force -Recurse -Confirm:$false $directory2Delete在PowerShell ISE中不起作用,但在常规的PowerShell CLI中起作用。
我希望这能有所帮助。它快把我逼疯了。
推荐文章
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 是否有一种方法可以通过双击.ps1文件来使PowerShell脚本工作?
- PowerShell等价于grep -f
- “Write-Host”,“Write-Output”,或“[console]::WriteLine”之间的区别是什么?
- c#测试用户是否有对文件夹的写权限
- Powershell相当于bash的&号(&),用于分叉/运行后台进程
- PowerShell脚本在机器上返回。net框架的版本?
- 移动一个文件到服务器上的另一个文件夹
- 如何在PowerShell中获得MD5校验和
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符
- 用Python遍历目录
- 使用PowerShell删除超过15天的文件
- 如何删除整个文件夹和内容?