How to delete all temp files using powershell
Asked Answered
H

4

9

Anyone knows how to delete all temp files using powershell.

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

I tired this code but it couldn't work. Can you suggest me any better way to perform the same.

Hourly answered 26/7, 2018 at 3:37 Comment(1)
Are you trying to delete a TEMP folder inside the C:\Users\<username>\AppData\Local\Temp folder?Mineraloid
B
12

If you don't want to see any errors, you could use the -ErrorAction switch like this:

Remove-Item -Path $env:TEMP\* -Recurse -Force -ErrorAction SilentlyContinue
Bushmaster answered 26/7, 2018 at 6:22 Comment(2)
warning! this command will delete the Temp folder itself so you will not have C:\Users\<username>\AppData\Local\Temp exists after command is executed. You can try to use $env:temp\* to delete the Temp folder content only.Ethelynethene
Most of the times it's nice to only delete files older than some days -- e.g. Get-ChildItem -File -Recurse -ErrorAction SilentlyContinue -Path $env:TEMP | ?{ $_.LastWriteTime -lt (Get-Date).AddDays(-$days)} | rm -Force -ErrorAction SilentlyContinue and then delete empty directories: https://mcmap.net/q/262649/-how-to-recursively-remove-all-empty-folders-in-powershellCotsen
R
4

To empty TEMP folder and leave the folder in place, you should use this command:

Remove-Item $env:TEMP\* -Recurse

If you don't want to type so much, you can use also shorter version:

rm $env:TEMP\* -r
Rebus answered 28/9, 2020 at 12:2 Comment(0)
M
1

Just use this:

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

Of course you will get access errors if any of the files you are deleting are actually being used by the system.

Mineraloid answered 26/7, 2018 at 4:21 Comment(0)
M
-2

I'm running PS as LOCAdmin and run following command

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

works for me :)

Mcmahan answered 24/11, 2020 at 21:3 Comment(1)
Downvoted for plagiarising from devblogs.microsoft.com/scripting/… You should follow the guidelines on referencing other sources at stackoverflow.com/help/referencingJohny

© 2022 - 2024 — McMap. All rights reserved.