从任务计划程序运行时,PowerShell脚本逻辑不起作用

时间:2019-02-26 16:22:14

标签: powershell task scheduled-tasks

在发布此问题之前,我已经检查了许多其他类似的问题,但是这些问题的答案并没有帮助我,因此请尝试我的特定问题。

我有一个脚本,该脚本在PowerShell控制台中运行时有效,但在按计划任务运行时却不起作用。该脚本(请参见下文)执行以下操作:

获取自指定调度任务的上次运行以来目标计算机上的事件日志。 检查是否指定了任何事件ID⇒如果没有,则不执行任何操作 ⇒如果找到该事件ID中的1个或多个,则重新启动机器。 然后,它会检查指定的URL是否有200响应,并在经过指定的尝试次数后是否警告该URL没有给出200响应。

似乎失败的地方是远程事件日志的返回-当作为任务运行时,它什么也没回来,因此脚本决定不需要重新启动并且什么也不做。

在控制台运行和任务计划程序运行之间,帐户运行以及源计算机和目标计算机都是相同的。

任务配置XML:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2019-02-04T16:53:13.8715362</Date>
    <Author>**** *****</Author>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT5M</Interval>
        <Duration>P1D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2019-02-04T16:48:02.1285494</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>**** *****</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
    <UseUnifiedSchedulingEngine>false</UseUnifiedSchedulingEngine>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe</Command>
      <Arguments>-noprofile -ExecutionPolicy Bypass -command "&amp;{D:\scripts\script.ps1; exit $LASTEXITCODE}"</Arguments>
    </Exec>
  </Actions>
</Task>

脚本代码:

#  Original script credit:   https://gallery.technet.microsoft.com/PowerShell-Script-to-Send-873dc0b6

$global:MachineName="servername.ucles.internal"

# This must be set to the name of the scheduled task running the script
$taskname = "Taskname"
$smtpServer = "smtp0"

$eventIDToMonitor = "3005"
$eventMessageToMonitor = "An unhandled exception has occurred."
$urlToCheck = "https://www.google.com"

$emailTo****** = "manning.i@domain.org.uk"
$emailToMIMs = "manning.i@domain.org.uk"
$emailSubjectUsers = "An issue has been found with the ****** web application server causing the site to be unavailable and this will now be restarted automatically.  **TEST MESSAGE PLEASE IGNORE**"
$emailSubjectUsersSiteUp = "**** ***** site back up.  '**TEST MESSAGE PLEASE IGNORE**"
$emailSubjectUsersSiteStillDown = "There has been an unexpected problem encountered in restarting **** *****, a call has been logged with the *** Service Desk.  **TEST MESSAGE PLEASE IGNORE**"
$emailSubject******SiteUp = "The server $MachineName has been successfully restarted. Service Desk please do not log an incident.  **TEST MESSAGE PLEASE IGNORE**"
$emailSubject******IgnoreAlerts = "The server $MachineName has been rebooted. Please do not log an incident for this alert. If you receive any alert related to ******, please do not log anything.  **TEST MESSAGE PLEASE IGNORE**"
$emailSubject***ServiceSiteStillDown = "The server $MachineName has been restarted and but the monitored URL $urlToCheck is not responding. ***** please log a Priority 2 incident and assign this to ******.  **TEST MESSAGE PLEASE IGNORE**"
$emailBody***ServiceSiteStillDown = "Service line : ****<br>Service : ****<br>Category : *****"

$emailFrom = (Get-Content env:computername) + "@domain.something"

# Below numbers should relate to the frequency of the scheduled task
# For example, if your scheduled task runs every 5 minutes, and $checkPauseSeconds is set to 60, with $checkRepeatLimit set to 4, this mean:
# Script will run every fiveminutes, and if there is a reboot, will wait a minute, check the url for 200 response, then do this 3 more times before triggering an alert that the server hasn't come back

$checkPauseSeconds = "60"
$checkRepeatLimit = "4"

$debugSubject = "debugging - script running"
Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $debugSubject -BodyAsHtml -SmtpServer $smtpServer
$EntryType = @("Warning","Error","Information")
# Only get events since the last run of the task
$taskinfo = Get-ScheduledTask -TaskName $taskname | Get-ScheduledTaskInfo
$eventLogs = Get-EventLog -ComputerName $MachineName -LogName Application -EntryType $EntryType -After $taskinfo.LastRunTime
Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $eventLogs.Count -BodyAsHtml -SmtpServer $smtpServer
foreach ($Event in $eventLogs) {
    if ($Event.EventID -eq $eventIDToMonitor) {
        $rebootFlag++
    } else {
    }
}
Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $debugSubject -BodyAsHtml -SmtpServer $smtpServer -Body $rebootFlag
if (!$rebootFlag -eq $false) {
    Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $emailSubjectUsers -BodyAsHtml -SmtpServer $smtpServer
    Send-MailMessage -From $emailFrom -To $emailto****** -Subject $emailSubject******IgnoreAlerts -BodyAsHtml -SmtpServer $smtpServer
    shutdown.exe /m \\$MachineName -r

    do {
        $webStatus = Invoke-WebRequest -uri $urlToCheck
        Start-Sleep -Seconds $checkPauseSeconds
        $webStatusCheckCount++
    } until ($webStatus.StatusCode -eq 200 -or $webStatusCheckCount -eq $checkRepeatLimit)

    if ($webStatus.StatusCode -eq 200) {
        Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $emailSubjectUsersSiteUp -BodyAsHtml -SmtpServer $smtpServer
        Send-MailMessage -From $emailFrom -To $emailTo****** -Subject $emailSubject******SiteUp -BodyAsHtml -SmtpServer $smtpServer
    } else {
        Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject $emailSubjectUsersSiteStillDown -BodyAsHtml -SmtpServer $smtpServer
        Send-MailMessage -From $emailFrom -To $emailTo****** -Subject $emailSubject***ServiceSiteStillDown -Body $emailBody***ServiceSiteStillDown -BodyAsHtml -SmtpServer $smtpServer
    }
} else {
    # Do nothing as we didn't reboot.
    Send-MailMessage -From $emailFrom -To $emailToMIMs -Subject "Reboot flag was null" -BodyAsHtml -SmtpServer $smtpServer
}

0 个答案:

没有答案