powershell 示例(探测端口并重启程序)

###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

 

posted @ 2017-06-22 09:50  记忆的红皮书  阅读(1034)  评论(0编辑  收藏  举报