Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Console Application Installer - Schedule Windows Task

Does anyone know how to create an installation project using Visual Studio 2010 that creates a Windows Scheduler task? I'm building an installer for a Console Application that needs to run every X minutes, and it would be nice for the customer not to have to schedule it manually.

Thanks!

like image 510
bopapa_1979 Avatar asked Mar 21 '26 07:03

bopapa_1979


1 Answers

in Wix (.wixproj) you can do it in a CustomAction, written in Jscript, that invokes Schtasks.exe .

I don't know about VS2010's support of WIX, I think it is built-in.

The custom action module (the .js file) should have a function to run a schtasks command, something like this:

function RunSchtasksCmd(command, deleteOutput) {
    deleteOutput = deleteOutput || false;
    var shell = new ActiveXObject("WScript.Shell");
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var tmpdir = fso.GetSpecialFolder(SpecialFolders.TemporaryFolder);
    var tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName());
    var windir = fso.GetSpecialFolder(SpecialFolders.WindowsFolder);
    var schtasks = fso.BuildPath(windir,"system32\\schtasks.exe") + " " + command;

    // use cmd.exe to redirect the output
    var rc = shell.Run("%comspec% /c " + schtasks + "> " + tmpFileName, WindowStyle.Hidden, true);
    if (deleteOutput) {
        fso.DeleteFile(tmpFileName);
    }
    return {
        rc : rc,
        outputfile : (deleteOutput) ? null : tmpFileName
    };
}

And then, use that from within the custom action function itself, something like this

var r = RunSchtasksCmd("/Create Foo bar baz");
if (r.rc !== 0) {
    // 0x80004005 == E_FAIL
    throw new Error("exec schtasks.exe returned nonzero rc ("+r.rc+")");
}

var fso = new ActiveXObject("Scripting.FileSystemObject");
var textStream = fso.OpenTextFile(r.outputfile, OpenMode.ForReading);

// Read from the file and parse the results.
while (!textStream.AtEndOfStream) {
    var oneLine = textStream.ReadLine();
    var line = ParseOneLine(oneLine); // look for errors?  success?
}
textStream.Close();
fso.DeleteFile(r.outputfile);

Some people say writing CA's in script is the wrong thing to do, because they are hard to maintain, hard to debug, or it's hard to do them right. I think those are bad reasons. CA's implemented correctly in script, work well.

like image 70
Cheeso Avatar answered Mar 22 '26 22:03

Cheeso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!