2013-04-05 50 views
0

我有一个脚本,用于检查远程服务器上的服务,以及在服务关闭时发送电子邮件。但是,如果服务器在脚本运行时发生故障,可能会导致脚本运行很长时间。有什么办法可以加快这个过程吗?我希望脚本能够继续下去直到完成。任何帮助将不胜感激。另外,如果在这个脚本中还有其他的东西可以改进,请让我知道,因为我是PowerShell的新手。谢谢!当服务器关闭时,Powershell get-service会运行很长

#****************** Function To Send E-Mail ******************# 

function sendEmail { 

send-mailmessage -to "recipient <[email protected]>" -from "sender <[email protected]>" ` 
-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 
     } 
    } 
} 
} 

回答

0

在致电Get-Service之前,请检查服务器是否联机。以下内容将发送一次ping以查看服务器是否在线,如果不在,将跳至$servers中的下一项。将此放在您拨打Get-Service的行的前面。

if ((Test-Connection -computername $server -quiet -count 1) -eq $false) { 
    continue; 
} 
+0

谢谢alroc!剧本的运行时间约为01:20,与以前相比有了很大的改进。连接失败时为测试连接添加电子邮件通知是否明智?如果是这样,我会把它放在当前的脚本中? – jdc2060 2013-04-05 19:59:45

+0

如果我的回答解决了您的问题,请将其标记为答案。无论您是否添加电子邮件通知,这取决于您 - 您的要求是什么?如果您决定这么做,可以在'if'语句内(在continue之前)执行它,或者如果您不想自己发送垃圾邮件,请将服务器名称添加到列表中,然后通过电子邮件发送列表结束。 – alroc 2013-04-06 02:14:39

+0

会做alroc。再次感谢您的帮助! – jdc2060 2013-04-08 13:24:30

相关问题