2

I'm using C# and PowerShell to automate git commands to sync a lot of repositories. I found two ways of executing powershell commands:

However, the documentation is really sparse on exactly what the difference is between the two methods. I have created two examples below using each of the two methods:

Running PowerShell commands with AddScript():

using (PowerShell powershell = PowerShell.Create())
{
    powershell.AddScript(@"git pull");
    var result powershell.Invoke();
}

Running PowerShell commands with AddCommand():

using (PowerShell powershell = PowerShell.Create())
{
    var command = new PSCommand();
    command.AddStatement().AddCommand("git").AddArgument("pull");
    powershell.Commands = command;
    var result = powershell.Invoke();
}

Both of the examples work as expected, but I would like to know what the difference is between AddScript() and Addcommand(). When would I use one method over the other? Are there advantaged/disadvantages with using one over the other?

6
  • 1
    None in this case. git pull is just a single command. A script can contain multiple commands, loops, pipes etc, like Get-ChildItem "X:\" -directory | Select FullName | Export-Csv "DirectoriesInX.csv". That's 3 piped commands that write subfolder names in X: to a CSV file Commented Oct 10 at 7:18
  • Thanks for commenting. I have many more powershell commands that I'm running in addititon to git pull, the git pull was just an example. I'm wondering if there's anything special I should consider when choosing between AddScript() or AddCommand() to add all the commands in C#. Commented Oct 10 at 8:53
  • 2
    It depends mostly on what you're gonna do next - if you want to do complex analysis and/or (re-)construction of command chains then explicitly using AddCommand(...).AddArgument(...) for every single command element makes sense. If you're just going to immediately invoke a hardcoded script, AddScript(...) is perfectly fine. Commented Oct 10 at 9:45
  • 2
    A script is a bunch of text that's interpreted into commands. It really depends on what you have already, and how complex it is. It's probably slightly faster to use AddCommand as no interpretation needed. Commented Oct 10 at 11:29
  • 1
    While the question part of the linked duplicate isn't a duplicate of your question, I'm hoping the answer there addresses your question. Commented Oct 11 at 0:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.