以下是实现 强制清除打印队列 的 PowerShell 脚本,包含管理员权限检查和详细操作提示:
powershell
<#
.SYNOPSIS
强制清除Windows打印队列的PowerShell脚本(需管理员权限)
#>
# 检查是否以管理员身份运行
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "请右键选择'以管理员身份运行'此脚本!" -ForegroundColor Red
exit
}
try {
# 1. 停止打印后台服务
Write-Host "正在停止 Print Spooler 服务..." -ForegroundColor Cyan
Stop-Service -Name Spooler -Force -ErrorAction Stop
Write-Host "服务已停止。" -ForegroundColor Green
# 2. 删除所有打印队列文件
Write-Host "正在清理打印缓存..." -ForegroundColor Cyan
$printerFolder = "$env:SystemRoot\System32\spool\printers"
if (Test-Path $printerFolder) {
Remove-Item -Path "$printerFolder\*.*" -Force -ErrorAction Stop
Write-Host "缓存文件已删除。" -ForegroundColor Green
} else {
Write-Host "未找到打印缓存目录,跳过清理。" -ForegroundColor Yellow
}
# 3. 重新启动服务
Write-Host "正在启动 Print Spooler 服务..." -ForegroundColor Cyan
Start-Service -Name Spooler -ErrorAction Stop
Write-Host "服务已启动。" -ForegroundColor Green
# 完成提示
Write-Host "`n操作成功完成!请检查打印机队列是否已清空。" -ForegroundColor Green
}
catch {
Write-Host "`n发生错误: $_" -ForegroundColor Red
exit 1
}
使用说明
- 保存脚本:将代码复制到记事本,保存为
Clear-PrintQueue.ps1
。 - 运行脚本:
- 右键点击脚本文件,选择 使用 PowerShell 运行(必须管理员身份)。
- 预期效果:
- 自动停止打印服务 → 清理残留任务 → 重启服务,全程输出状态提示。
注意事项
- 如果报错
无法加载文件,因为此系统禁止执行脚本
,请先执行:powershellSet-ExecutionPolicy RemoteSigned -Scope Process -Force
- 部分安全软件可能拦截操作,临时关闭防护软件后再试。