可在Windows 11中通过PowerShell批量清理临时文件:一、管理员运行命令清除%TEMP%目录;二、扩展清理C:\Windows\Temp;三、封装为CleanTemp.ps1脚本并启用执行策略;四、用任务计划实现每周日自动清理。

如果您希望在 Windows 11 中通过 PowerShell 快速、批量清理临时文件,则可能是由于系统或应用程序生成的临时数据长期未清理,导致磁盘空间被大量占用。以下是使用 PowerShell 执行清理的具体方法:
一、运行基础PowerShell清理命令
PowerShell 提供了直接操作文件系统的权限与灵活性,可一次性清除当前用户临时目录下的大部分非锁定文件。该方法不依赖图形界面,适合习惯命令行操作的用户,且执行效率高。
1、以管理员身份打开“Windows PowerShell”(右键开始菜单 → 选择“Windows PowerShell(管理员)”或“终端(管理员)”)。
2、输入以下命令并按回车执行:
Get-ChildItem -Path $env:TEMP -Recurse -Force | Where-Object {!$_.PSIsContainer} | Remove-Item -Force -ErrorAction SilentlyContinue
3、等待命令执行完成(无提示即表示已尽力删除所有可删文件)。
二、扩展清理系统级临时目录
除用户级 %TEMP% 外,Windows 还存在系统级临时路径(如 C:\Windows\Temp),该路径下常驻安装程序缓存和系统服务临时文件,需提升权限后方可访问和清理。
1、确保仍处于管理员 PowerShell 环境中。
2、输入以下命令并按回车执行:
Get-ChildItem -Path "$env:windir\Temp" -Recurse -Force | Where-Object {!$_.PSIsContainer} | Remove-Item -Force -ErrorAction SilentlyContinue
3、若提示“访问被拒绝”,说明部分文件正被系统进程占用,可忽略;其余文件将被清除。
三、创建并执行可复用的PowerShell脚本
为避免每次重复输入长命令,可将清理逻辑封装为 .ps1 脚本,并设置为可执行,便于后续一键调用或配合任务计划定期运行。
1、用记事本新建文本文件,粘贴以下内容:
# CleanTemp.ps1\n$UserTemp = $env:TEMP\n$SystemTemp = "$env:windir\Temp"\nWrite-Host "正在清理用户临时文件..." -ForegroundColor Cyan\nGet-ChildItem $UserTemp -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {!$_.PSIsContainer} | Remove-Item -Force -ErrorAction SilentlyContinue\nWrite-Host "正在清理系统临时文件..." -ForegroundColor Cyan\nGet-ChildItem $SystemTemp -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {!$_.PSIsContainer} | Remove-Item -Force -ErrorAction SilentlyContinue\nWrite-Host "清理完成。" -ForegroundColor Green
2、将文件保存为 CleanTemp.ps1(注意保存类型选“所有文件”,编码为 UTF-8)。
3、在管理员 PowerShell 中,执行:Set-ExecutionPolicy RemoteSigned -Scope CurrentUser(仅需执行一次,允许本地脚本运行)。
4、随后运行脚本:.\CleanTemp.ps1(注意路径前的点和反斜杠)。
四、结合任务计划实现自动清理
通过 Windows 任务计划程序,可让 PowerShell 脚本按指定周期(如每周日)静默运行,无需人工干预,持续防止临时文件堆积。
1、在管理员 PowerShell 中,运行以下命令注册定时任务:
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\CleanTemp.ps1"'\n$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At '03:00'\n$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive\n$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable\nRegister-ScheduledTask 'AutoCleanTemp' -Action $action -Trigger $trigger -Principal $principal -Settings $settings
2、请先将 CleanTemp.ps1 移动至 C:\Scripts\ 目录(需提前手动创建)。
3、命令执行成功后,可在“任务计划程序库”中看到名为 AutoCleanTemp 的任务。










