如何在C#CMD中运行,并具有密码管理权限,然后将所有输出保存为字符串?
我想在CMD中运行runas/user:Administrator C:\Info.bat“。管理员用户需要密码(“密码”)。当我确认密码时,我得到了我想要保存到字符串中的数据 这是我的密码:如何在C#CMD中运行,并具有密码管理权限,然后将所有输出保存为字符串?,c#,batch-file,cmd,C#,Batch File,Cmd,我想在CMD中运行runas/user:Administrator C:\Info.bat“。管理员用户需要密码(“密码”)。当我确认密码时,我得到了我想要保存到字符串中的数据 这是我的密码: // admin password with secure string var pass = new SecureString(); pass.AppendChar('p'); pass.AppendChar('a'); p
// 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();
“不工作”到底是什么意思?你有错误吗?或者其他一些意外行为?请尝试此操作并让我知道=>
startInfo.Arguments=“/user:Administrator\”cmd/K C:\\Info.bat\”代码>感谢@er shoaib运行C:\Info.bat。我应该添加上述代码作为您问题的答案吗?@LukaToni,我更新我的答案以读取cmd数据以字符串,请查看答案中的编辑部分:)