Thursday, March 18, 2010

Query Scheduled Tasks The Hard Way

Because the CIM/WMI model is still an unfinished work in progress, I’ve once again had to resort to making some ugly crap code to work around a giant hole in the model. In this case it’s the lack of a model counterpart to the Scheduled Tasks collection.  This is NOT the same as the Win32_ScheduledJobs or the AT command output.  I’m talking about SCHTASKS.exe and the Windows Scheduled Tasks utility.  Anyhow, the klunky workaround here is to ride the SCHTASKS command like a whipping boy and make it dump a text file, then turn around and do a crude (but effective) string parsing and crank it out in XML form.  Enjoy.
'****************************************************************
' Filename..: xml_scheduled_tasks.vbs
' Author....: David M. Stein
' Date......: 03/18/2010
' Purpose...: query Scheduled Tasks (not WMI/Jobs/AT) --> XML out
'****************************************************************

Const tempfile = "c:\temp\schtasks.txt"
Const computer = ""

Const ForReading = 1
Const ForWriting = 2

Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

If computer <> "" Then
cmdstr = "cmd /c schtasks /query /s \\" & computer & " /v /fo list >" & tempfile
Else
cmdstr = "cmd /c schtasks /query /v /fo list >" & tempfile
End If

retval = objShell.Run(cmdstr, 1, True)

If objFSO.FileExists(tempfile) Then
Dim linecount, objFSO, objFile, ln, strLine

linecount = 0
wscript.echo ""

Set objFile = objFSO.OpenTextFile(tempfile, ForReading)
Do Until objFile.AtEndOfStream
strLine = Trim(objFile.Readline)

If Left(strLine, 9) = "HostName:" Then
hostname = Mid(strLine, 39)
wscript.echo vbTab & ""

ElseIf Left(strLine, 9) = "TaskName:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
wscript.echo vbTab & vbTab & "" & hostname & ""

ElseIf Left(strLine, 15) = "Scheduled Type:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 9) = "Schedule:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 12) = "Task To Run:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 8) = "Comment:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 12) = "Run As User:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 11) = "Start Time:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 11) = "Start Date:" Then
wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""

ElseIf Left(strLine, 17) = "Power Management:" Then
wscript.echo vbTab & "
"

End If
linecount = linecount + 1

Loop
objFile.Close
Set objFSO = Nothing

wscript.echo "
"

Else
wscript.echo "fail: file not found"
End If

No comments:

Post a Comment