我有一个脚本,用于检查远程服务器上的服务,并在服务关闭时发送电子邮件。但是,如果在脚本运行时服务器发生故障,可能会导致脚本运行很长时间。有什么方法可以加快这个过程吗?我希望脚本继续执行直到完成。任何帮助将不胜感激。另外,如果我在这个脚本中还有什么可以改进的,请让我知道,因为我是 powershell 新手。谢谢!
#****************** Function To Send E-Mail ******************#
function sendEmail {
send-mailmessage -to "recipient <admin@mail.com>" -from "sender <admin@mail.com>" `
-subject "$eSubject" `
-body "$eBody" -smtpServer mail.smtpServer.com
}
#****************** Set Variables ******************#
$erroractionpreference = "SilentlyContinue"
$date = Get-Date
$servicesPath = "C:\path_to_file\services.txt"
$serversPath = "C:\path_to_file\servers.txt"
$services = Get-Content $servicesPath
$servers = Get-Content $serversPath
#****************** Check Services And Send E-Mail ******************#
foreach ($service in $services) {
foreach ($server in $servers)
{
#Check If Service Exist On Server
$checkService = Get-Service -ComputerName $server -DisplayName $service
#If The Service Exists Evaluate Status
if($checkService)
{
if ($checkService.status -notlike "Running")
{
#Get Server Last Boot Up Time, Set E-Mail Subject And Body, And Send E-Mail
$OperatingSystem = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $server
$LastBootUp = $OperatingSystem.ConvertToDateTime($OperatingSystem.LastBootUpTime)
$eSubject = "$service DOWN on $server"
$eBody = "$date`r`n$service DOWN on $server`r`nLast bootup time for $server is: $LastBootUp"
sendEmail
}
}
}
}