服务器关闭时,Powershell get-service运行很长时间

时间:2013-04-05 18:55:02

标签: powershell-v2.0

我有一个脚本用于检查远程服务器上的服务,如果服务已关闭,则发送电子邮件。但是,如果服务器在脚本运行时发生故障,则可能导致脚本运行很长时间。有没有办法加快这个过程?我希望脚本继续直到完成。任何帮助将不胜感激。此外,如果还有其他任何我可以改进的脚本,请告诉我,因为我是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
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

在致电Get-Service之前,请检查服务器是否在线。以下将发送一个ping以查看服务器是否在线,如果不是,将跳转到$servers中的下一个项目。将其放在您拨打Get-Service的行之前。

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