如何在具有管理员权限和密码的C#CMD中运行,然后将所有输出保存到字符串中



我想在CMD中运行"runas/user:Administrator C:\Info.bat">。管理员用户需要("pass"(的密码。当我确认密码时,我得到了要将其保存到字符串中的数据。

这是我的代码:

// admin password with secure string
var pass = new SecureString();
pass.AppendChar('p');
pass.AppendChar('a');
pass.AppendChar('s');
pass.AppendChar('s');
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("CMD");
startInfo.Verb = "runas";
//go to user -> Administrator and then to file C:\Info.bat (not working)
startInfo.Arguments = "/user:Administrator C:\Info.bat";
startInfo.Password = pass;
startInfo.UseShellExecute = false;
p.StartInfo = startInfo;
// save all output data to string
p.Start();

为什么第二个参数不能运行C:\Info.bat?

如何将所有cmd输出文本保存为字符串?

谢谢你的帮助。

您需要修改流程参数,如下所示

startInfo.Arguments = "/user:Administrator "cmd /K C:\Info.bat"";

/K参数,它告诉CMD.exe打开,运行指定的命令,然后保持窗口打开。

您也可以使用。

/C参数,它告诉CMD.exe打开,运行指定的命令,然后在完成后关闭。

编辑:

在这里,您可以读取字符串变量中info.bat文件的输出。

var pass = new SecureString();
pass.AppendChar('p');
pass.AppendChar('a');
pass.AppendChar('s');
pass.AppendChar('s');
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("CMD");
startInfo.Verb = "runas";
startInfo.Arguments = "/user:Administrator "cmd /C  C:\info.bat"";
startInfo.Password = pass;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;   
p.StartInfo = startInfo;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

相关内容

最新更新