如何使用PowerShell删除所有临时文件

8

有人知道如何使用Powershell删除所有临时文件吗?

Get-ChildItem $env:TEMP\TEMP | Remove-Item -confirm:$false -force -Recurse

我尝试了这段代码但不起作用。你能否建议我执行相同操作的更好方法。


1
你是否试图删除C:\Users\<username>\AppData\Local\Temp文件夹中的TEMP文件夹? - Sid
4个回答

11
如果您不想看到任何错误,可以像这样使用-ErrorAction开关:
Remove-Item -Path $env:TEMP\* -Recurse -Force -ErrorAction SilentlyContinue

3
警告!执行此命令将会删除 Temp 文件夹本身,因此在命令执行后,您将不再拥有 C:\Users\<username>\AppData\Local\Temp 文件夹。您可以尝试使用 $env:temp\* 命令只删除 Temp 文件夹中的内容。 - oleksa
大多数情况下,仅删除几天前的文件是很好的选择--例如 Get-ChildItem -File -Recurse -ErrorAction SilentlyContinue -Path $env:TEMP | ?{ $_.LastWriteTime -lt (Get-Date).AddDays(-$days)} | rm -Force -ErrorAction SilentlyContinue 然后删除空目录:https://dev59.com/YV4b5IYBdhLWcg3w1UvL#28637537 - ndemou

3
清空 TEMP 文件夹并保留该文件夹,您应该使用以下命令:
Remove-Item $env:TEMP\* -Recurse

如果您不想打那么多字,也可以使用更短的版本:

rm $env:TEMP\* -r

1

只需使用这个:

Remove-Item -Path $env:TEMP -Recurse -Force

如果你删除的文件实际上正在被系统使用,那么当然会出现访问错误。


-2

我正在以LOCAdmin身份运行PS,并运行以下命令

PS C:\Windows\system32>$tempfolders = @(“C:\Windows\Temp\*”, “C:\Windows\Prefetch\*”, “C:\Documents and Settings\*\Local Settings\temp\*”, “C:\Users\*\Appdata\Local\Temp\*”)
PS C:\Windows\system32>Remove-Item $tempfolders -force -recurse

对我来说可以工作:)


因为从 https://devblogs.microsoft.com/scripting/weekend-scripter-use-powershell-to-clean-out-temp-folders/ 抄袭,所以被踩了。你应该遵循 https://stackoverflow.com/help/referencing 上的引用其他来源的指南。 - Anthony Geoghegan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接