0

my intention is to start a Powershell process with admin rights to pass it arguments in C#. For that I have written following piece of code

public void PassCommand(string command)
    {
        Process process = new Process();
        process.StartInfo.FileName = "powershell.exe";
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.Verb = "runas";
        process.Start();
        process.StandardInput.WriteLine(command);
        process.StandardInput.Flush();
        process.StandardInput.Close();
        Console.WriteLine(process.StandardOutput.ReadToEnd());
    }

I have read in some other articles thatI just have to add this line process.StartInfo.Verb = "runas";. But unfortunately it does not work. The Powershell starts without admin rights. Can someone help me to get this solved?

Marcel Müller
  • 368
  • 3
  • 17
  • 2
    You must use `UseShellExecute = true`, and you can't redirect input and output, if you want to elevate the powershell. Instead you must elevate your own process first. – Lasse V. Karlsen Jul 21 '20 at 09:41
  • So if I write a console app that calls the powerShell to pass it commands, my console app must be elevated? How can I configure that to start this process always with admin rights? – Marcel Müller Jul 21 '20 at 09:48
  • Create a shortcut to it I would assume. – Lasse V. Karlsen Jul 21 '20 at 09:49
  • 1
    @MarcelMüller [Create an application manifest](https://stackoverflow.com/questions/6050478/how-do-i-create-edit-a-manifest-file) and [set the `level` attribute of `requestedExecutionLevel` to `requireAdministrator`](https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-securityoverview) – Mathias R. Jessen Jul 21 '20 at 11:08

0 Answers0