使用来自 C# 的参数以管理员身份运行 CMD [英] Running CMD as administrator with an argument from C#

查看:56
本文介绍了使用来自 C# 的参数以管理员身份运行 CMD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以管理员身份运行 cmd.exe,参数来自 C# 以防止 UAC 弹出窗口.这是必要的,以便将其用作自动安装过程.我传入的命令只是一个安装文件 (.exe) 的路径,带有 /q 用于安静安装.

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.

当我运行这段代码时,有一个 CMD 弹出窗口,但它运行时好像没有执行任何东西.

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;
    }
}

推荐答案

你的命令至少有一个问题,这一行:

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

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

应该是:

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

此外,这不会作为一个完全自动化的过程工作,因为它会要求管理员密码,而在 Windows Vista 和更新版本中,该密码是未知的.

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.

这篇关于使用来自 C# 的参数以管理员身份运行 CMD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆