8

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.

Mshah17
  • 83
  • 1
  • 2
  • 8
  • 1
    Are you trying to delete a `TEMP` folder inside the `C:\Users\\AppData\Local\Temp` folder? – Sid Jul 26 '18 at 04:23

4 Answers4

11

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
ndemou
  • 4,691
  • 2
  • 30
  • 33
TobyU
  • 3,718
  • 2
  • 21
  • 32
  • 3
    warning! this command will delete the `Temp` folder itself so you will not have `C:\Users\\AppData\Local\Temp` exists after command is executed. You can try to use `$env:temp\*` to delete the `Temp` folder content only. – oleksa Feb 12 '20 at 10:56
  • 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://stackoverflow.com/a/28637537/1011025 – ndemou Aug 31 '22 at 14:13
3

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
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.

Sid
  • 2,586
  • 1
  • 11
  • 22
-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 :)

Kerlc
  • 1
  • Downvoted for plagiarising from https://devblogs.microsoft.com/scripting/weekend-scripter-use-powershell-to-clean-out-temp-folders/ You should follow the guidelines on referencing other sources at https://stackoverflow.com/help/referencing – Anthony Geoghegan Aug 03 '21 at 15:51