PowerShell脚本失败时有什么选择?

时间:2013-10-28 13:15:25

标签: powershell-v2.0 exit-code

不想使用我的APC附带的APC软件我已经编写了PowerShell脚本来监控我的UPS,并在电池电量达到30%时启动服务器的关机顺序。

该脚本通过USB重定向在虚拟化服务器上​​运行。窗口永远保持打开状态,因为它监视主UPS电池电量的WMI输入。该脚本运行得很漂亮,但有几次我登录到服务器并注意到屏幕上出现以下错误

Get-WmiObject : Call was canceled by the message filter. (Exception from HRESULT: 0x80010002 (RPC_E_CALL_CANCELED))
At C:\Users\user\Desktop\upsmonitor.ps1:38 char:27
+     $binfo = Get-WMIObject <<<<  -class Win32_Battery -computername $system -namespace root\cimv2
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

我认为这是由WMI活动中的一个小点引起的 - 我读过论坛,说这是由WMI崩溃引起的。无论如何,这是有问题的,因为如果脚本需要运行并且它出错了那么它对我没有好处。经常检查服务器并不理想,所以我想要一种方法

  • 失败时重新执行脚本
  • 至少在脚本失败时通知我

我已阅读-ErrorAction开关,但我不确定如何在我的情况下实施它,或者它是否适用。通常情况下我会玩脚本直到我能够解决问题,但它只是真的出现在我的生产环境中,并且它不一致。我可能需要几个月的时间来解决这个问题,等待错误发生,希望我的修复工作正常。

我很感激你们提供的任何帮助。

脚本如下所示。

## Variable Declaration
cls
$system = "."
$namespace = "root\CIMV2"

#SMTP Variables (for e-mail notifications)
$emailFrom = "ups@domain.com"
$emailto = "me@domain.com"
$subject = "UPS Notifications"
$PSEmailServer = "10.0.0.100"

#Check to see if the event log source exists, and create it if it doesn't
$sourceExists = get-eventlog -list | where-object {$_.logdisplayname -eq "UPS Monitor"}
if (! $sourceExists) {
    new-eventlog -LogName "UPS Monitor" -source "UPS Monitor"
    }

#Send the administrator a message to inform them of monitoring
$initialStatus = Get-WMIObject -class Win32_Battery -computer $system -namespace $namespace
send-mailmessage -From $emailFrom -To $emailTo -Subject $subject -Body "UPS Monitor Online: Monitoring UPS Status."
echo "UPS Monitor Online - Currently Monitoring UPS Status. DO NOT CLOSE THIS WINDOW!"

$eruntime = $initialstatus.estimatedruntime

#What's the status of the Battery upon starting the script
if ($initialStatus.batterystatus -eq 2) {
    echo "Battery Status : On AC Power"
    echo "Estimated Time remaining on charge : $eruntime minutes"
} elseif($initialStatus.batterystatus -eq 1) {
    echo "Battery Status : Discharging"
    echo "Estimated Time remaining on charge : $eruntime minutes"
    }

write-eventlog -logname "UPS Monitor" -Source "UPS Monitor" -EntryType Information -EventID 1 -Message "UPS Monitor Online: Currently Monitoring UPS Status"

while($true)
   {
    $binfo = Get-WMIObject -class Win32_Battery -computername $system -namespace root\cimv2
    if($binfo.BatteryStatus -eq 2) {  
       #On AC Power - No action required
        }
      if($binfo.BatteryStatus -eq 1){
            #If UPS status is 1, UPS is discharging - Notifications will begin at 80% Battery Level
            #echo "Battery Charge Percentage : " $binfo.EstimatedChargeRemaining
             if($binfo.EstimatedChargeRemaining -eq 80){
                #When the battery level gets to 80% write an event to the event log and e-mail the administrator
                write-eventlog -logname "UPS Monitor" -Source "UPS Monitor" -EntryType Information -EventID 1 -Message "Power Failure Detected - 80% Battery Life Remaining"
                send-mailmessage -From $emailFrom -To $emailTo -Subject $subject -Body "Power Failure Detected; Servers on Battery Power. Battery level is 80%"
                start-sleep -seconds 30
                 }
             elseif($binfo.EstimatedChargeRemaining -eq 60){
                #When the battery level gets to 60% write an event to the event log and e-mail the administrator
                write-eventlog -logname "UPS Monitor" -Source "UPS Monitor" -EntryType Information -EventID 1 -Message "Power Failure Detected : 60% Battery Life Remaining"
                send-mailmessage -From $emailFrom -To $emailTo -Subject $subject -Body "Power Failure Detected; Servers on Battery Power. Battery level is 60%"
                start-sleep -seconds 30
                 }
             elseif($binfo.EstimatedChargeRemaining -eq 40){
                #When the battery level gets to 40% write an event to the event log and e-mail the administrator and warn of shutdown
                write-eventlog -logname "UPS Monitor" -Source "UPS Monitor" -EntryType Information -EventID 1 -Message "Power Failure Detected : 40% Battery Life Remaining"
                send-mailmessage -From $emailFrom -To $emailTo -Subject $subject -Body "Power Failure Detected & Reserve battery is critical. Servers will be restarted at 30% battery life if AC power is not resumed"
                start-sleep -seconds 30
                }
              elseif($binfo.EstimatedChargeRemaining -le 30){
                #When the battery level gets to 30% being shutting down servers
                write-eventlog -logname "UPS Monitor" -Source "UPS Monitor" -EntryType Information -EventID 1 -Message "Critical Battery Threshold Reached : Commencing Shutdown of servers"
                send-mailmessage -From $emailFrom -To $emailTo -Subject $subject -Body "Power Failure Detected & Critical Battery Threshold has been Reached. Commencing Shutdown of Servers"
                start-sleep -seconds 15
                stop-computer -cn (Get-Content C:\Users\User\Desktop\serverlist.txt) -Force
                }

        }
    }

1 个答案:

答案 0 :(得分:0)

您可以简单地使用try catch块并在发生错误时在catch块中定义细节。