Логика сценария PowerShell не работает при запуске из планировщика задач - PullRequest
0 голосов
/ 26 февраля 2019

Я проверил ряд других подобных вопросов перед тем, как опубликовать это, но ответы на них мне не помогли, поэтому пробую свой конкретный.

У меня есть скрипт, который работает при запуске вКонсоль PowerShell, но не при запуске в качестве запланированной задачи.Сценарий (см. Ниже) выполняет следующие действия:

Получает журнал событий на целевом компьютере с момента последнего запуска указанной запланированной задачи.Проверяет любые идентификаторы событий, указанные ⇒, если их нет, ничего не делают ⇒, если он находит 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
}
...