###restartAPP.ps1###
$log="D:\xxxx\xxxx\xxxx.log.txt"
$execFile="C:\Program Files (x86)\xxxx\xxxx\xxxx.exe"
$Ipaddress='10.x.x.x'
$Port=80
# 探测端口
$t = New-Object Net.Sockets.TcpClient
try
{
$t.Connect($Ipaddress,$Port)
}
catch{}
# 如果可以连接端口
if($t.Connected)
{
add-content "$log" "$(Get-Date): Port $Port is operational."
}
# 否则
else
{
# 连接断开,需要重连.
add-content "$log" "$(Get-Date): Port $Port is closed."
# 注销除管理员外的登录用户
$SERVER="$(hostname)"
try {
query user /server:$SERVER 2>&1 | select -skip 1 | Select-String "administrator" -notMatch | foreach {
logoff ($_ -split "\s+")[-6] /server:$SERVER
}
}
catch {}
# 重启程序
stop-process -name xxxx -force
Start-Sleep -Seconds 10
Start-Process -FilePath "$execFile"
add-content "$log" "$(Get-Date): xxxx has been restarted."
}
运行:powershell -ExecutionPolicy Bypass -File restartAPP.ps1
设置计划任务:如果提示“已有一个实例在运行”,可以考虑修改运行方式为“允许多实例运行”。
运行时指定要运行的程序是powershell,参数是-ExecutionPolicy Bypass -File restartAPP.ps1