开启的服务在一些意外的情况下会自动挂掉,这就需要一个守护进程来循环的检查服务,在它挂掉的情况下,自动启动它。
整个工程有3个文件,第一个conf.txt是配置文件,配置需要守护的进程,例如:
配置注意事项:
1.timeinterval是指每隔多少秒检查一次
2.startpath中的路径要用\分隔
3.processname要和任务管理器中的进程名一样(区分大小写),去掉.exe
{
timeinterval:"10",
process:[
{processname:"sqlservr",startpath:"C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\sqlservr.exe"},
{processname:"Ssms",startpath:"C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\Ssms.exe"}
]
}
第二个是Powershell的脚本
$current_dir = Split-Path -Parent $MyInvocation.MyCommand.Definition; $log_file = "${current_dir}monitor.log" # 脚本日志最大为10M $log_max_size = 10*1024*1024 $CONF = (Get-Content "${current_dir}conf.txt") | ConvertFrom-Json $timeinterval=$CONF.timeinterval function proce(){ for($i=0;$i -lt $CONF.process.Length;$i++) { Checstart $CONF.process[$i].processname $CONF.process[$i].startpath }} function log($content) { $date = Get-Date -UFormat "%Y-%m-%d %H:%M:%S" Add-Content -Path $log_file -Value "$date : $content" $log_file_size = (Get-ChildItem $current_dirmonitor.log).Length if ( $log_file_size -gt $log_max_size) { if ( Test-Path $current_dirmonitor.log.bak ) { Remove-Item $current_dirmonitor.log.bak } Copy-Item $log_file $current_dirmonitor.log.bak Clear-Content $log_file } } function Checstart($process_name,$start_up_file) { Get-Process | findstr $process_name > $null if ( $? -eq "True" ) { log "process ${process_name} is running!" } else { log "process ${process_name} is not exist, now to start it." Start-Process -FilePath $start_up_file if ( $? -eq "True" ) { log "start ${process_name} succefully!" } else { log "start ${process_name} failed!" } } } while(1 -eq 1) { proce Start-Sleep -Seconds $timeinterval }
第三个是执行记录的日志(脚本跑起来后自动会创建)。
让这个ps脚本排个Job开机启动即可。
如果是installutil安装的服务,要使用 start-service 服务名 启动,
function Checstart($process_name,$start_up_file) { Get-Process | findstr $process_name > $null if ( $? -eq "True" ) { log "process ${process_name} is running!" } else { log "process ${process_name} is not exist, now to start it." Start-service $start_up_file if ( $? -eq "True" ) { log "start ${process_name} succefully!" } else { log "start ${process_name} failed!" } } }
配置文件中的processname,startpath都写成服务名即可
{ timeinterval:"10", process:[ {processname:"sqlservr",startpath:"sqlservr"} ] }
缺陷:要是这个job的进程自己挂掉了,该如何防止这种情况呢?