# Restore PowerShell's default execution policy, which does not allow any scripts to be executed by default
# Set-executionpolicy Default-force
#设置Powershell的执行策略为, you can execute any script
# Set-executionpolicy Unrestricted-force
#定义一个发送邮件的函数sendEmail (recipient address, sender address, mail server, mail server port, mail server login password, mail header, message body)
Function SendEmail ([string] $to, [string] $from, [string] $smtpServer, [int] $port, [string] $password, [string] $subjet, [ String] $body)
{
#生成一个. NET mail client object, parameter is the address and port of the server
$SMTPClient = New-object Net.Mail.SmtpClient ($SmtpServer, 25)
#使用SSL加密
$SMTPClient. Enablessl = $true
#提供邮件客户端类使用的用户名和密码
$SMTPClient. Credentials = New-object System.Net.NetworkCredential ($from, $password)
#调用send方法发送邮件
$SMTPClient. Send ($from, $to, $Subject, $Body)
}
#调用函数测试
#sendEmail "Recipient email Address" "Sender email Address" "smtp.163.com" 25 "password" "Mail Header" "Message body"
#检查服务状态的函数, if one or more services stop then return FALSE, the parameter is the name of the service, you can specify multiple names separated by spaces
Function Checkservice () {
#循环检查参数传递进来的每一个服务, if there is a service status other than "Running", return "sorry", note that the return value here is different from C #
if ($args | Foreach {get-service-name $_ | where Status-ne Running}) {
Write-output Sorry
}
else{
Write-output OK
}
}
#调用函数测试
#checkService Xlserviceplatform Themes
#启动服务的函数, the parameter is a service name that needs to be detected and started, you can specify multiple parameters, separated by a space
#功能为循环检查传递进来的每一个服务, if the status of the service is not "Running", start the service
Function StartService () {
$args | Foreach {get-service-name $_ |where status-ne Running | Start-service}
}
#调用函数测试
#startService Xlserviceplatform Themes
#检测服务器服务
#定义要检查的服务名称, note that the display name is not
$service _name= "Xlserviceplatform", "Themes"
$flag =0
Do
{
$TorF =checkservice $service _name
#第一次执行
if ($TorF-eq "Sorry") {
StartService $service _name
SendEmail "Inbox @qq.com" "Outgoing @163.com" "smtp.163.com" 25 "Outgoing mailbox Password" "Server Alarm" "There is one or more services not working properly, we have tried to start the service, if you receive this message more than once, please check your server immediately." "
$flag = $flag +1
}
#检测间隔, the time unit is seconds.
Sleep (10)
}while ($flag-le 3) #循环退出条件
This article from the "Secret Flying Tiger Space" blog, declined to reprint!
PowerShell detects and starts multiple services