How to Execute complex batch command on the fly
I am looking for a way to run DOS/windows batch directly from C# code without saving it as .BAT file before. I'm mainly interested to run DOS command with a combination of stdin stream.
Let's say I need execute something like that:
echo 'abcd' | programXXX.exe -arg1 --getArgsFromStdIn
After that programXXX.exe will take 'abcd' string as -arg1
What I'm doing now is just create bat file in TMP directory and running it, deleting after execution.
What I need is run it "on the fly" just from .NE开发者_JS百科T code without saving to file previously. (Main reason is security, but also do not want to leave rubbish when program crashes etc)Do you know how to achieve that?
You can use Process.Start
.
It will take several parameters, and you can pass through command line parameters to it.
I would offer two suggestions
- use redirected IO and launch the program from in your code
- you can use power shell like in this tutorial
A switch to PowerShell (PSH) would give you much greater ability to execute commands. PSH executes in process, and multiple command lines can be executed in a single runspace
(scope/context) with full control over input and output object pipelines:
var runspace = RunspaceFactory.CreateRunspace();
PSSnapInException pex;
var loadedSnapIn = Runspace.RunspaceConfiguration.AddPSSnapIn(SnapInName, out pex);
runspace.Open();
var pipe = runspace.CreatePipeline(commandline);
var output = pipe.Invoke();
This creates the runspace, loads a snapin (i.e. extra custom commands), sets up a command and executes it, collecting the collection of returned objects.
精彩评论