新编写了计划任务,开机自启动Mysql,重复检测直到启动成功。
目录在C:\scripts
实际检测执行 check_mysql.ps1
$ErrorActionPreference = "Continue"
$ServiceName = "MySQL"
$RetryInterval = 10
$BaseDir = "C:\scripts"
$LogDir = "$BaseDir\logs"
$LogFile = "$LogDir\check_mysql.log"
function Write-Log {
param ([string]$Message)
try {
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $LogFile -Value "$time $Message"
} catch {
# ignore logging errors
}
}
try {
if (!(Test-Path $LogDir)) {
New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
}
Write-Log "Script started"
while ($true) {
try {
$service = Get-Service -Name $ServiceName -ErrorAction Stop
} catch {
Write-Log "Service not found: $ServiceName"
break
}
if ($service.Status -eq "Running") {
Write-Log "MySQL is running, exit"
break
}
Write-Log "Service status: $($service.Status), try start"
Start-Service -Name $ServiceName -ErrorAction SilentlyContinue
Write-Log "Sleep $RetryInterval seconds"
Start-Sleep -Seconds $RetryInterval
}
Write-Log "Script finished normally"
}
catch {
Write-Log "Fatal error: $($_.Exception.Message)"
}
exit 0
自动创建计划任务执行 管理员执行create_mysql_task.ps1
# ================= 配置 =================
# 管理员执行powershell -ExecutionPolicy Bypass -File C:\scripts\create_mysql_task.ps1
$TaskName = "AutoStartMySQL"
$ScriptPath = "C:\scripts\check_mysql.ps1"
# PowerShell 启动参数
$Action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-ExecutionPolicy Bypass -NoProfile -File `"$ScriptPath`""
# 触发器:开机启动
$Trigger = New-ScheduledTaskTrigger -AtStartup
# 任务设置
$Settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Hours 1)
# 使用 SYSTEM 权限运行(最稳定)
Register-ScheduledTask `
-TaskName $TaskName `
-Action $Action `
-Trigger $Trigger `
-Settings $Settings `
-User "SYSTEM" `
-RunLevel Highest `
-Force