-5

Is there any advantage to using a PowerShell script over a batch file?

By which I mean, if I have something which will run in either, is there anything to warrant detecting if PowerShell is installed and using it over a batch file if it is?

SCHTASKS works in exactly the same manner on both. Given that, is there any differentiator between them?

BanksySan
  • 27,362
  • 33
  • 117
  • 216

1 Answers1

0

The following code executes the same code via both processes:

internal class Program
{
    private static void Main()
    {
        const string COMMAND = @"SCHTASKS /QUERY /XML ONE";

        Collection<PSObject> psObjects;
        using (var ps = PowerShell.Create())
        {
            ps.AddScript(COMMAND);
            psObjects = ps.Invoke();
        }

        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                FileName = "cmd.exe",
                Arguments = "/C " + COMMAND
            }
        };

        process.Start();

        string cmdTasks;
        using (var reader = process.StandardOutput)
        {    
            cmdTasks = reader.ReadToEnd();
        }
    }
}

The response object from the two approaches differs. The Process.Start() approach returns a string, which I would have to parse whereas invoking PowerShell gives me a collection of PSObject objects.

BanksySan
  • 27,362
  • 33
  • 117
  • 216