首页 > 解决方案 > 如何在 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 输出文本保存到字符串

感谢帮助。

标签: c#batch-filecmd

解决方案


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

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();

推荐阅读