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?
git pullis just a single command. A script can contain multiple commands, loops, pipes etc, likeGet-ChildItem "X:\" -directory | Select FullName | Export-Csv "DirectoriesInX.csv". That's 3 piped commands that write subfolder names inX:to a CSV filegit pull, thegit pullwas just an example. I'm wondering if there's anything special I should consider when choosing betweenAddScript()orAddCommand()to add all the commands in C#.AddCommand(...).AddArgument(...)for every single command element makes sense. If you're just going to immediately invoke a hardcoded script,AddScript(...)is perfectly fine.AddCommandas no interpretation needed.