One of our users has an occasional requirement to manually run a scheduled task on a server. I wanted him to do this without logging on via RDP. Scheduled tasks can be run remotely using the SVHTASKS program (on Windows XP and Server 2003) so I started writing a VB Script to call this app. The tricky part was capturing the output of the command and displaying that back to the user, so he would know if it was a success or failure. It turns out this is actually quite difficult to do, so I hacked up various other scripts I found on the web until I eventually got this to work. The working version is below.
A copy you can download is here - I'm having a problem with character encoding on the site which is ruining code snippets like the one below.
[lang='vb']
strServer = "your_server_name"
strTask = "task_name"
Continue = MsgBox ("Scheduled job " & strTask & " will run on " & strServer & ". Are you sure?",vbYesNo + VBQuestion, "Run scheduled task")
If Continue = vbYes then
Const OpenAsASCII = 0
Const FailIfNotExist = 0
Const ForReading = 1
sExe = "SCHTASKS /Run /S " & strServer & " /TN " & strTask
Set oShell = CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
sTemp = oShell.ExpandEnvironmentStrings("%TEMP%")
sTempFile = oFSO.GetSpecialFolder(2).ShortPath & "\" & oFSO.GetTempName
oShell.Run "%comspec% /c " & sExe & " " & sTempFile, 0 , True
Set fFile = oFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsASCII)
' capture output and inject into a variable
sResults = fFile.ReadAll
fFile.Close
oFSO.DeleteFile(sTempFile)
MsgBox sResults , vbInformation , "Result"
Else
wscript.quit
End If
[/lang]

