Deprecated features of the task scheduler

I was reviewing antivirus exclusions for various components – IIS, WSUS, Windows, SQL, ConfigMgr – and found that I’d like to be spammed whenever my server complains that it’s running out of memory…

…not necessarily due to the antivirus (mis)configuration or the fact that my applications are intensively consuming available resources. Actually, it’s a best practice to monitor the performance of servers when you know that the following can happen: (Sorry, I couldn’t resist to publish a selection of my favorites known issues 😉 )

  • Memory leak in the svchost process which hosts the Task Scheduler service: http://support.microsoft.com/kb/2855594/en-us
  • Summary
    When you have a scheduled task configured with the option “Do not store password. The task will only have access to local resources”, each time the task runs, it may leak 4 KB memory (and internally it’s 64 KB) in the svchost.exe instance which hosts the Task Scheduler service.

    This normally won’t be an issue, but if the machine keeps running for long time and the task runs frequently, the leaked memory would become considerable eventually, which may cause the svchost.exe process to be instable.

    As that instance of the svchost.exe process also hosts other services like User Profile Service, you may encounter symptoms like logon failure (get the error message “The User Profile Service service failed the logon. No more threads can be created in the system.”)

    More information
    To work around the issue, you may uncheck the option “Do not store password. The task will only have access to local resources”.

  • High CPU usage on a Windows Server 2012-based server when many client computers connect to the server: http://support.microsoft.com/kb/2830448/en-us
  • Symptoms:
    Assume that many client computers that have unique IP addresses connect to a Windows Server 2012-based server. For example, more than 100,000 client computers that have unique IP addresses connect to the server. In this situation, the network traffic stalls, and the server experiences high CPU usage.

    Cause:
    This issue occurs because the periodic cleanup routine for the local cache holds lots of locks during operations that consume lots of resources.

    Resolution: apply Hotfix

  • The Windows.edb file grows very large in Windows 8 or Windows Server 2012: https://support.microsoft.com/kb/2838018/en-us
  • Symptoms
    In Windows 8 or Windows Server 2012, the Windows Search Service may bloat the Windows.edb file. When this issue occurs, the Windows.edb file grows to a very large size and consumes lots of disk space. In some instances, the file size can be larger than 50 gigabytes (GB).

    Resolution: apply 2836988 Windows 8 and Windows Server 2012 update rollup: May 2013

    Note This update is preventative, but not corrective. To reduce the size of a Windows.edb file that is already affected by this issue, you must rebuild the search index after you install this update.

  • Windows Server 2012: Server Manager can consume a large amount of private memory http://support.microsoft.com/kb/2851710/en-us
  • Symptoms:

    Consider the following scenario:

    You are running Windows Server 2012 and Server Manager is running in one or more sessions
    There is high load on the system and a process or processes are logging a large number of events to the event log on the system within the Server Manager retention period (default 24 hours)

    In the above scenario, Server Manager can continue to consume memory on the system until all memory is exhausted and the server becomes unresponsive.

    Cause:
    The minimum event retention period in Server Manager is 24 hours. Server Manager combines data from various sources within memory. The behavior occurs because Server Manager does not observe Eventlog quotas nor does it release the events from memory when they are outside of the display filters for Server Manager (even with a manual refresh). Server Manager frees the event data from memory after the retention period set by the user. The default retention period is 24 hours.

    Error conditions on the system further exacerbate the issue due to the higher rate of event generation and subsequently a higher rate of memory consumption.

    Resolution:

    To resolve this issue, install the Windows 8 and Windows Server 2012 cumulative update 2811660: March 2013

    Workaround:
    To workaround this issue, Microsoft recommends investigating the source of the increased event logging and resolving the conditions generating the events.

    Alternatively, closing Server Manager resolves the issue.

Basically, I wanted to receive a ton of mails whenever an anormal resource consumption occurs. To achieve this, I needed to create a scheduled task running whenever an event 2004 is logged. And I found 2 limitations along the road:

  • Sending email from the task scheduler has been deprecated on Windows 2012


  • The Performance Team published today: What’s New in Task Scheduler for Windows 8 & Server 2012 which confirmed that the workaround to send messages is now the Send-MailMessage cmdlet. Perfect, that’s what I did 😎 …(see below).

  • The New-ScheduledTaskTrigger is unable to create a trigger based on events
  • My approach to workaround this issue consists in first creating the task with regular Powershell cmdlets from the ScheduledTasks module, then exporting the task in XML, removing the TimeTrigger childnode, replacing it with an EventTrigger node and updating the XML definition of the task. Well, it isn’t as easy as it sounds… Here’s what I did:

    # Define the command parameter of powershell.exe
    $command = "`"& { Send-MailMessage -From my.server@my.org -To my.email@my.org -SmtpServer my.smtp.server -Subject 'Resource Exhaustion on myserver' }`""
    # note: to avoid backtick, the command can be encoded
    
    $A = New-ScheduledTaskAction -Execute $env:systemroot\System32\WindowsPowerShell\V1.0\PowerShell.exe -Argument "-NoProfile -ExecutionPolicy BypPass -Command $command"
    
    $T = New-ScheduledTaskTrigger -Once -At (Get-Date)
    
    $P = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
    
    # By default we have PT72H = 3 days, set it to 1 hour 
    $S = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1)
    
    $D = New-ScheduledTask -Action $A -Principal $P -Trigger $T -Settings $S
    
    Register-ScheduledTask -TaskName "Resource-Exhaustion" -InputObject $D
    

    The first step is was the easy part….

    # We need a namespace to use XPath
    $xmlNameTable = new-object System.Xml.NameTable
    $xmlNameSpace = new-object System.Xml.XmlNamespaceManager($xmlNameTable)
    $xmlNameSpace.AddNamespace("task","http://schemas.microsoft.com/windows/2004/02/mit/task")
    
    # Get the XML definition of the task as a string
    $xmlstr = (Get-ScheduledTask -TaskPath "\" -TaskName "Resource-Exhaustion"| Export-ScheduledTask)
    
    # Load the above string as XML document
    $xml = New-Object System.Xml.XmlDocument
    $xml.LoadXml($xmlstr)
    
    # Replace the chdild node (the timetrigger) by my EventTrigger node:
    ($xml.DocumentElement.SelectSingleNode("//task:Triggers",$xmlNameSpace)).InnerXml = @'
    <EventTrigger xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <Enabled>true</Enabled>
      <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="System"&gt;&lt;Select Path="System"&gt;*[System[Provider[@Name='Microsoft-Windows-Resource-Exhaustion-Detector'] and EventID=2004]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
    </EventTrigger>
    '@
    
    # Update the task using a ComObject
    $TASK_UPDATE_FLAG = 0x4
    $TaskService = New-Object -com schedule.service
    $TaskService.Connect($env:COMPUTERNAME)
    $taskDef = $TaskService.GetFolder('\').GetTask('Resource-Exhaustion').Definition
    
    $taskDef.XmlText = ($xml.OuterXml)
    
    $TaskService.GetFolder('\').RegisterTaskDefinition(
        'Resource-Exhaustion',
        $taskDef,
        $TASK_UPDATE_FLAG,
        $null,
        $null,
        $taskDef.Principal.LogonType
    )
    

    I don’t know if there’s an easiest way of doing it or simplifying the above code. But, if you know, please leave a comment 🙂

    Advertisements

    One thought on “Deprecated features of the task scheduler

    1. In my case here is what I did:
      1. In Event Viewer, I looked for the event ID I would like to add in Task Scheduler, right-clicked, selected ‘Attach Task to this Event’
      2. I then went to Task Scheduler and looked for the task I created
      3. Inside the task, under Action, I created a new Action, Start a program, and called my Powershell script to send an email. Basically, the command was powershell.exe -file “c:\sendmail.ps1”

      The powershell script then contained the send mail commands. In my case also, I did not use the -Port, -UseSSL as my SMTP server is using default configuration.

      ##############################################################################
      $From = “alert@email.com”
      $To = “user@email.com”
      $Cc = “yourboss@email.com”
      $Attachment = “C:\temp\Some random file.txt”
      $Subject = “your subject”
      $Body = “your email body”
      $SMTPServer = “smtprelay.company.org”
      $SMTPPort = “52”

      Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential (Get-Credential) -Attachments $Attachment
      ##############################################################################

      Please check my wordpress site for the complete detail.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s