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

查看:1586
本文介绍了以管理员身份使用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 + "\""


b $ b

此外,这将不能作为一个完全自动的过程,因为它会要求管理员的密码,在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天全站免登陆