C# &引用;“多步骤”;在C中使用CMD.exe时的命令#
我试图在c#脚本中使用“multi-step”命令,例如,“net user usrname*”命令包含3个步骤来输入密码,然后进行验证,我不知道进程运行时是否可以发送额外的参数 我的代码:C# &引用;“多步骤”;在C中使用CMD.exe时的命令#,c#,windows,cmd,C#,Windows,Cmd,我试图在c#脚本中使用“multi-step”命令,例如,“net user usrname*”命令包含3个步骤来输入密码,然后进行验证,我不知道进程运行时是否可以发送额外的参数 我的代码: Process p = new Process(); p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName
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();
您可以用“&”连接每个命令。例如,“cmd/k回波测试1和回波测试2” 编辑: 不久前,我创建了一个远程控制/远程管理解决方案,它使用相同的技术,允许您通过web门户对远程计算机运行批处理和PowerShell脚本。如下面的屏幕截图所示,它工作正常 执行命令的C#可以在这里找到:
重定向标准输入并将其输入字符串。RedirectStandardInput=true并将字符串写入p.StandardInput流我将尝试此技术。基本方法是创建.bat文件或使用&&或| |运算符告诉Cmd.exe您指定了多个命令。请注意错误处理,当其中一个命令失败时,这会导致无法诊断的混乱。问题是我不想同时执行多个命令,我只想在执行后在命令中输入参数,例如,当您在cmd中键入日期时,控制台会问您一个值。谢谢您的回答,我试过了,但没用,所以我不知道该怎么做。你能详细解释一下“没用”吗?专一性很重要。:)
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);
}