Search code examples
c#cmdinstallationadmin

Running CMD as administrator with an argument from C#


I want to run cmd.exe as administrator with arguments from C# in order to prevent a UAC popup. This is necessary in order to use it as an automated installation process. The command I am passing in is simply a path to installation file (.exe) with /q for quiet installation.

When I run this code, there is a CMD popup, but it runs as if it didn't execute anything.

public static string ExecuteCommandAsAdmin(string command)
{

    ProcessStartInfo procStartInfo = new ProcessStartInfo()
    {
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = true,
        FileName = "runas.exe",
        Arguments = "/user:Administrator cmd /K " + command
    };

    using (Process proc = new Process())
    {
        proc.StartInfo = procStartInfo;
        proc.Start();

        string output = proc.StandardOutput.ReadToEnd();

        if (string.IsNullOrEmpty(output))
            output = proc.StandardError.ReadToEnd();

        return output;
    }
}

Solution

  • There is at least one problem with your command, this line:

    Arguments = "/user:Administrator cmd /K " + command
    

    Should be:

    Arguments = "/user:Administrator \"cmd /K " + command + "\""
    

    Also, this won't work as a fully automated process, because it will ask for the Administrator's password which in Windows Vista and newer is not known.