"多步" C#中使用CMD.exe时的命令

时间:2017-12-16 16:02:38

标签: c# windows cmd

我试图使用"多步骤" c#脚本中的命令,例如命令" net user usrname *"包含3个步骤来输入密码然后验证,我不知道在进程运行时是否可以发送额外的参数

我的代码:

Process p = new Process();
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C " + command;
p.StartInfo.WorkingDirectory = startupFolder;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();

1 个答案:

答案 0 :(得分:2)

您可以将每个命令与"&"连接起来。例如," cmd / k echo Test 1&回声测试2"。

编辑:

我之前创建了一个远程控制/远程管理解决方案,它使用相同的技术,允许您通过Web门户对远程计算机运行批处理和PowerShell脚本。如下面的屏幕截图所示,它可以工作。

enter image description here

执行命令的C#可以在这里找到:https://github.com/Jay-Rad/InstaTech_Client/blob/master/InstaTech_Service/Socket.cs#L614

if (cmdProcess == null || cmdProcess.HasExited)
{
    var psi2 = new ProcessStartInfo("cmd.exe", "/k " + command);
    psi2.RedirectStandardOutput = true;
    psi2.RedirectStandardInput = true;
    psi2.RedirectStandardError = true;
    psi2.UseShellExecute = false;
    psi2.WorkingDirectory = Path.GetPathRoot(Environment.SystemDirectory);

    cmdProcess = new Process();
    cmdProcess.StartInfo = psi2;
    cmdProcess.EnableRaisingEvents = true;
    cmdProcess.OutputDataReceived += async (object sender, DataReceivedEventArgs args) =>
    {
        jsonMessage.Status = "ok";
        jsonMessage.Output = args.Data;
        await SocketSend(jsonMessage);

    };
    cmdProcess.ErrorDataReceived += async (object sender, DataReceivedEventArgs args) =>
    {
        jsonMessage.Status = "ok";
        jsonMessage.Output = args.Data;
        await SocketSend(jsonMessage);
    };
    cmdProcess.Start();
    cmdProcess.BeginOutputReadLine();
    cmdProcess.BeginErrorReadLine();
}
else
{
    cmdProcess.StandardInput.WriteLine(command);
}