简体   繁体   中英

Batch file v PowerShell script

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM