Query Scheduled Tasks

3 12 2009

Recently I was tasked to create a script to query all servers in our farm for their scheduled tasks information. Instinctively I opened up notepad and started writing a script to use WMI (Windows Management Instrumentation). Using CIM Studio I found the Win32_ScheduledJob class which at first glance looked like it was the one I needed. I ran the script only to get no data back and as a bonus no errors.  A quick Google search and a little reading and I discovered that the Win32_Scheduledjob class would only enumerate scheduled tasks that were created using the AT command. Since this is 2009 all scheduled tasks in our environment were created using the windows GUI. The best way to query these tasks is through the use of the schtasks.exe command. Fortunately the schtasks.exe allows for connection to systems so I could run the command locally and gather data from the servers. I set to work creating a script based on this and it worked out very well. A little Excel magic and I had the information I needed!

Const READ = 1

set objShell = WScript.CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")

‘open a text file containing a list of all systems to query
Set objFile = objFSO.GetFile("servers.txt")
set objStream = objFile.OpenAsTextStream(READ, -2)

‘open a text file for the output
set objLog = objFSO.OpenTextFile("tasks.csv", 8, True)

‘Read the contents of the servers.txt file one line at a time
While not objStream.AtEndOfStream
    strServer = objStream.Readline

   ‘Run the schtasks.exe command against the server
    set objCMD = objShell.Exec("schtasks.exe /Query /S " & strServer & " /FO CSV /NH /V")
    ‘capture the output and write it to tasks.csv
    objLog.WriteLine objCMD.stdOut.ReadAll()

‘Let me know when you are done doing my bidding




2 responses

14 07 2011

you cannot use /NH switch with /FO CSV
it took me an hour to figure out why your script isn’t working

13 10 2011

Infact you can only use the /NH exclusively with the /FO CSV or /FO TABLE

/FO format
A value that specifies the output format. The valid values are TABLE, LIST, and CSV.
A value that specifies that the column header should not be displayed in the output. This is valid only for TABLE and CSV formats.

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

%d bloggers like this: