c# - 如何在 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();
推荐阅读
- c# - 将列表的值分配给另一个列表
- reactjs - 替换变量 onclick 反应
- scala - 如何修复 [错误] igaGatling$ - 运行崩溃的 java.lang.IllegalArgumentException:要求失败:没有设置场景?
- python - 为什么第一个代码的复杂性高于第二个代码?
- python - python中的“%%bash”命令有什么作用?
- angular - 在 Angular 7 中,是否可以创建两个指向同一个 HTML 模板的组件?如果是的话,我怎么能用反应形式呢?
- python - 用于替换值python的JSON操作
- windows - 如何获取字符串列表中的每个字符串?
- r - R ezperm() 错误信息:替换有 9 行,数据有 3
- python - Adyen 加密信用卡数据 [python] [请求]