# 设置 Docker 自动清理计划任务 # 用途:创建 Windows 计划任务,每周自动清理 Docker 数据 # 使用:以管理员身份运行此脚本 # 检查管理员权限 $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Host "❌ 此脚本需要管理员权限" -ForegroundColor Red Write-Host "请右键点击 PowerShell 并选择'以管理员身份运行'" -ForegroundColor Yellow exit 1 } Write-Host "=== 设置 Docker 自动清理计划任务 ===" -ForegroundColor Cyan # 获取脚本路径 $scriptPath = Join-Path $PSScriptRoot "docker-cleanup.ps1" if (!(Test-Path $scriptPath)) { Write-Host "❌ 未找到清理脚本: $scriptPath" -ForegroundColor Red exit 1 } Write-Host "`n清理脚本路径: $scriptPath" -ForegroundColor Gray # 检查是否已存在任务 $taskName = "Docker Weekly Cleanup" $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue if ($existingTask) { Write-Host "`n⚠️ 计划任务已存在" -ForegroundColor Yellow $overwrite = Read-Host "是否覆盖现有任务? (Y/N)" if ($overwrite -eq 'Y' -or $overwrite -eq 'y') { Unregister-ScheduledTask -TaskName $taskName -Confirm:$false Write-Host "已删除现有任务" -ForegroundColor Yellow } else { Write-Host "操作已取消" -ForegroundColor Yellow exit 0 } } # 创建计划任务 Write-Host "`n创建计划任务..." -ForegroundColor Yellow # 任务操作 $action = New-ScheduledTaskAction ` -Execute "PowerShell.exe" ` -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`"" # 任务触发器(每周日凌晨 2 点) $trigger = New-ScheduledTaskTrigger ` -Weekly ` -DaysOfWeek Sunday ` -At 2am # 任务设置 $settings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries ` -DontStopIfGoingOnBatteries ` -StartWhenAvailable ` -RunOnlyIfNetworkAvailable:$false # 任务主体(使用当前用户) $principal = New-ScheduledTaskPrincipal ` -UserId $env:USERNAME ` -LogonType Interactive ` -RunLevel Highest # 注册任务 Register-ScheduledTask ` -TaskName $taskName ` -Action $action ` -Trigger $trigger ` -Settings $settings ` -Principal $principal ` -Description "每周自动清理 Docker 数据,防止 VHDX 文件过大" Write-Host "`n✅ 计划任务创建成功!" -ForegroundColor Green Write-Host "`n任务详情:" -ForegroundColor Cyan Write-Host " 任务名称: $taskName" -ForegroundColor Gray Write-Host " 执行时间: 每周日凌晨 2:00" -ForegroundColor Gray Write-Host " 执行脚本: $scriptPath" -ForegroundColor Gray Write-Host "`n你可以在'任务计划程序'中查看和管理此任务" -ForegroundColor Yellow Write-Host "或运行以下命令手动执行:" -ForegroundColor Yellow Write-Host " Start-ScheduledTask -TaskName '$taskName'" -ForegroundColor Cyan # 询问是否立即测试 $test = Read-Host "`n是否立即测试运行? (Y/N)" if ($test -eq 'Y' -or $test -eq 'y') { Write-Host "`n执行清理任务..." -ForegroundColor Yellow Start-ScheduledTask -TaskName $taskName Write-Host "任务已启动,请查看输出" -ForegroundColor Green }