如何用PowerShell实现Core Keeper服务器崩溃自动重启并保留退出功能
修改Core Keeper服务器脚本:实现崩溃自动重启+保留手动退出功能
以下是修改后的完整脚本,已添加进程监控与自动重启逻辑,同时保留原有的按q退出功能:
# Feel free to change these (see README), but keep in mind that changes to this file might be overwritten on update $CoreKeeperArguments = @("-batchmode", "-logfile", "CoreKeeperServerLog.txt") + $args $script:ckpid = $null function Quit-CoreKeeperServer { if ($script:ckpid -ne $null) { taskkill /pid $ckpid.Id Wait-Process -InputObject $ckpid Write-Host "Stopped CoreKeeperServer.exe" } } function Start-CoreKeeperServer { if (Test-Path -Path "GameID.txt") { Remove-Item -Path "GameID.txt" } $script:ckpid = Start-Process -PassThru -FilePath $PSScriptRoot\CoreKeeperServer.exe -ArgumentList $CoreKeeperArguments Write-Host "`nStarted CoreKeeperServer.exe (PID: $($ckpid.Id))" # Wait for GameID while (!(Test-Path -Path "GameID.txt")) { Start-Sleep -Milliseconds 100 } Write-Host -NoNewline "Game ID: " Get-Content "GameID.txt" } try { # 首次启动服务器 Start-CoreKeeperServer Write-Host "`nPress q to quit, DON'T close the window or the server process will just keep running" while ($true) { # 随机等待1-5秒,避免固定间隔的机械轮询 $sleepSeconds = Get-Random -Minimum 1 -Maximum 6 Start-Sleep -Seconds $sleepSeconds # 检查是否有按键输入 if ($Host.UI.RawUI.KeyAvailable) { $KeyInfo = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") # 按下q键则退出循环 if ($KeyInfo.VirtualKeyCode -eq 81) { break } } # 检查服务器进程是否已崩溃退出 if ($script:ckpid.HasExited) { Write-Host "`nCoreKeeperServer.exe (PID: $($ckpid.Id)) has crashed! Restarting..." Start-CoreKeeperServer } } } finally { Quit-CoreKeeperServer pause }
关键改动说明
- 新增
Start-CoreKeeperServer函数:把重复的启动逻辑封装成函数,方便崩溃后调用重启 - 替换原按键等待循环:改为同时监听按键输入+监控进程状态的循环,避免阻塞
- 随机间隔监控:用
Get-Random生成1-5秒的等待时间,减少系统资源占用 - 进程状态检查:通过
$ckpid.HasExited判断进程是否崩溃,一旦检测到就自动调用重启函数 - 优化路径写法:把原脚本中的
%0\..\替换为PowerShell标准的$PSScriptRoot(脚本所在目录),避免兼容性问题
内容的提问来源于stack exchange,提问作者Petr
相关产品推荐
相关产品推荐

