Retrieving scheduled tasks history

I had to check the history of custom scheduled tasks after OS upgrades on remote sites servers.

The scheduled task appeared to be working before the upgrade, looked good after the upgrade but was miserably failing at launch time:

Task Scheduler failed to load task “\My TaskName” at service startup. Additional Data: Error Value: 2147944189.
Whenever I launched the task manually, the schtasks.exe returned
ERROR: The system cannot find the file specified.

The solution consisted in deleting the task and creating it back. Creating it by overwriting the existing one didn’t make it actually.

I’ve used PowerShell to track precisely where the task was failing and where it succeeded after the above fix or not.
Because the bandwidth was quite low for the majority of remote sites servers, I had to limit the number of events and properties returned over remoting.

I’ve created the following XML query used with the Get-WinEvent cmdlet to query the history of my custom scheduled task (named ‘My TaskName’ below) in fairly decent amount of time.

Get-Content servers.txt | ForEach-Object { 
 $pc = $_
 try {
  invoke-command -ComputerName "$($_).my.fqdn" -ErrorAction Stop -ScriptBlock {
   try {
    $events = @(
     Get-WinEvent  -FilterXml @'
     <QueryList>
      <Query Id="0" Path="Microsoft-Windows-TaskScheduler/Operational">
       <Select Path="Microsoft-Windows-TaskScheduler/Operational">
        *[EventData/Data[@Name='TaskName']='\My TaskName']
       </Select>
      </Query>
     </QueryList>
'@  -ErrorAction Stop -MaxEvents 2
   ) 
   } catch {
     Write-Warning -Message "Failed to query $($env:computername) because $($_.Exception.Message)"
   }
   if ($events) {
    $events | Select MachineName,TimeCreated,Id,TaskDisplayName
   }
  } # end of scriptblock
 } catch {
  Write-Warning -Message "Failed to contact $pc because $($_.Exception.Message)"
 }
} | 
Select MachineName,TimeCreated,Id,TaskDisplayName |
Format-Table -AutoSize

Here is what it looks like when I query the history over the last 24 hours
(replace line 11 with this one in the above snippet and remove -MaxEvents 2 on line 15)

*[EventData/Data[@Name='TaskName']='\My TaskName'] and *[System[TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]

Advertisements

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