简体   繁体   English

以管理员身份在CMD中运行命令

[英]Running commands in CMD as administrator

Rules that i need to hold on to are the following: 我需要坚持的规则如下:

  1. run command prompt command as administrator as administrator运行命令提示符命令
  2. change directory (path is always the same) change directory (路径始终相同)
  3. run command net start something 运行命令net start something

Any thoughts on how can i do this programatically using C# ? 关于如何使用C#以编程方式进行此操作的任何想法?

Just for the record i am running console application built in .net 4.0 仅作记录,我正在运行内置于.net 4.0的控制台应用程序

I am using this function 我正在使用此功能

        private static void commandtorun(string commandexecuted)
    {
        string currentstatus;
        ProcessStartInfo startInfo = new ProcessStartInfo();
        Process myprocess = new Process();
        try
        {
            startInfo.FileName = "cmd"; //
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false; //'required to redirect
            //startInfo.CreateNoWindow = true; // '<---- creates no window, obviously
            myprocess.StartInfo = startInfo; //
            myprocess.Start(); //
            System.IO.StreamReader SR;
            System.IO.StreamWriter SW;
            Thread.Sleep(200);
            SR = myprocess.StandardOutput;
            SW = myprocess.StandardInput;
            SW.WriteLine(commandexecuted); // 'the command you wish to run.....
            SW.WriteLine("exit"); // 'exits command prompt window
            Thread.Sleep(200);
            currentstatus = SR.ReadToEnd();
            SW.Close();
            SR.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
            Console.ReadLine();
        }
        // throw new NotImplementedException();
    }

and i get access is denied when i call the function using this command: 当我使用以下命令调用该函数时,访问被拒绝:

commandtorun(@"cd c:\Program Files (x86)\folder1\folder2"); // change the folder because cmd always runs on different path
commandtorun("net start something"); run the COMMAND

I tried to run both commands in one statement but got the same error. 我试图在一个语句中运行两个命令,但出现相同的错误。

There are lots of problems here. 这里有很多问题。

You want to run the other process elevated, but your code does not take steps to make that happen. 您想运行另一个提升的进程,但是您的代码没有采取步骤来实现这一目标。 In order to do that you need to invoke your process with the runas verb, and UseShellExecute set to true . 为此,您需要使用runas动词来调用您的流程,并将UseShellExecute设置为true But you also want to re-direct which is why you set UseShellExecute to false . 但是您还想UseShellExecute ,这就是为什么将UseShellExecute设置为false

I see no compelling reason to redirect, so I think you can use true for UseShellExecute . 我没有令人信服的理由进行重定向,因此我认为可以将true用于UseShellExecute You are pumping an exit command into cmd.exe to terminate the process. 您正在将exit命令泵入cmd.exe以终止该过程。 You don't need to do that. 您不需要这样做。 Simply pass cmd.exe the /c argument and the process will close when it is done. 只需将cmd.exe传递给/c参数,该过程完成后将关闭。

These changes will allow you to remove those calls to Sleep() . 这些更改将使您可以删除对Sleep()那些调用。 Any time you call Sleep() you should ask yourself why you are doing it and if it can be avoided. 任何时候调用Sleep()您都应该问自己为什么这样做,以及是否可以避免。 Very few problems have Sleep() as the optimum solution. 很少有问题可以将Sleep()作为最佳解决方案。

You are trying to specify the working directory by executing cd . 您正在尝试通过执行cd指定工作目录。 That again is the wrong way to do it. 这又是错误的方法。 You can specify the working directory in the ProcessStartInfo object. 您可以在ProcessStartInfo对象中指定工作目录。 That's how you should do it. 那就是你应该怎么做。

Your design has you executing each command in a separate process. 您的设计要求您在单独的过程中执行每个命令。 That's a really poor way to go. 那是一个很糟糕的路要走。 You want to execute all the commands one after the other in a single instance of cmd.exe . 您要在cmd.exe的单个实例中一个接一个地执行所有命令。 Put the commands into a .bat or .cmd file and get cmd.exe to process that. 将命令放入.bat.cmd文件中,并获取cmd.exe进行处理。

Imagine if you carried on processing each command as a separate process. 想象一下,如果您继续将每个命令作为一个单独的过程进行处理。 How would the second process remember the working directory change that you made? 第二个过程如何记住您所做的工作目录更改? Would you really want your user to see a UAC dialog for each separate command? 您是否真的希望用户为每个单独的命令看到一个UAC对话框?

Having said all of that though, you are going about this the wrong way. 说了这么多,您将以错误的方式进行操作。 You are just trying to start a service. 您只是在尝试启动服务。 Yes, you do that with net start when you are working in the command line. 是的,当您在命令行中工作时,可以使用net start来实现。 But from a program you use the service API to start a service. 但是,您可以从程序中使用服务API来启动服务。 In other words I believe that you should throw away all of this code and call the service API. 换句话说,我相信您应该丢弃所有这些代码并调用服务API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM