Luka Toni
Luka Toni

Reputation: 187

How to run in C# CMD with admin rights with password and then save all output to a string?

I would like to run "runas /user:Administrator C:\Info.bat" in CMD. Admin user requires password which is ("pass"). When I confirm password I got data that I would like to save it into a string.

Here is my code:

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

Why second argument not working to run C:\Info.bat?

How can I save all cmd output text to a string?

Thanks for help.

Upvotes: 0

Views: 2890

Answers (1)

er-sho
er-sho

Reputation: 9771

You need to modify your process argument like below

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

/K argument, which tells CMD.exe to open, run the specified command, then keep the window open.

You may also use.

/C argument, which tells CMD.exe to open, run the specified command, then close when it's done.

Edit:

Here you can read output of your info.bat file in string variable.

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

Upvotes: 1

Related Questions