Skyl3r
Skyl3r

Reputation: 107

SCHTASKS Invalid Syntax in C# but working in CMD

I've got a command I'm trying to run through C# to get a list of tasks in CSV format from a bunch of computers.

To do this, I am using the SCHTASKS command with command redirection to a CSV. So I wrote this code in C# to do this for me:

        string commandGetStatus = "schtasks";
        string argumentsGetStatus = "/s:" + CompName +
                " /fo:csv" +
                " > \"" + @"\\BIG\OL\UNC\PATH\"+CompName+".csv" + "\"";

        getLatestTaskStatus.StartInfo.FileName = commandGetStatus;
        getLatestTaskStatus.StartInfo.Arguments = argumentsGetStatus;
        getLatestTaskStatus.StartInfo.CreateNoWindow = true;
        getLatestTaskStatus.StartInfo.RedirectStandardOutput = true;
        getLatestTaskStatus.StartInfo.RedirectStandardInput = true;
        getLatestTaskStatus.StartInfo.RedirectStandardError = true;
        getLatestTaskStatus.StartInfo.UseShellExecute = false;
        getLatestTaskStatus.Start();

It returns the output:

        ERROR: Invalid syntax.

        Type "SCHTASKS /?" for usage.

So I used StartInfo.FileName + " " + StartInfo.Arguments to print out the exact command that should be being executed. From there, I copy and pasted the command into CMD. Where it worked without a problem. This was the command + args:

        schtasks /s:COMPUTERNAME /fo:csv > "\\BIG\OL\UNC\PATH\COMPUTERNAME.csv"

I'm not sure what the problem is at this point.


My Solution

Luaan was absolutely correct about the problem. The command prompt redirection operator,>, is not available without using Command Prompt. Fortunately, the solution was quote simple and easy to implement. I reduced the argument variable to:

"/s:" + CompName + " /fo:csv"

And with standard output being redirected, I simply used:

            string output = process.StandardOuptut.ReadToEnd();
            File.WriteAllText(@"\\UNC\File\Path\" + myfile + ".csv", output);

Upvotes: 0

Views: 120

Answers (1)

Luaan
Luaan

Reputation: 63722

You explicitly disabled UseShellExecute - > is a shell operator, not something inherent to processes. It definitely isn't an argument. You need to read the output and write it out manually :)

Upvotes: 1

Related Questions