C# Process how to execute powershell command with admin permission

金利 张 20 Reputation points
2023-07-22T02:39:47.7533333+00:00

i want to using C# to start a hyper-v client from powershell with follow command

Start-VM -name "win11-Lite"

but this command use admin permission.

enter image description here

it's alright.

  1. using regular permissions to execute Or
  2. possible to have a pop-up authorization prompt window when executing

my code is

`

var processInfo = new System.Diagnostics.ProcessStartInfo
{
	Verb = "runas /trustlevel:0x20000",
	LoadUserProfile = true,
	FileName = "powershell.exe",
	Arguments = "Start-VM -name \"win11-Lite\"",
	RedirectStandardOutput = true,
	UseShellExecute = false,
	CreateNoWindow = true
};

var p = System.Diagnostics.Process.Start(processInfo);
while (!p.StandardOutput.EndOfStream)
{
	string line = p.StandardOutput.ReadLine();
	if (!string.IsNullOrEmpty(line))
	{
		rtb.Document.Blocks.Add(new Paragraph(new Run(line)));
	}
}

please help.

`

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,291 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,808 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 35,501 Reputation points
    2023-07-23T13:59:49.5433333+00:00

    As long as the user is a member of the Administrators group, this will launch an elevated process. You will get the UAC prompt.

                var processInfo = new System.Diagnostics.ProcessStartInfo
                {
                    Verb = "runas",
                    LoadUserProfile = true,
                    FileName = "powershell.exe",
                    Arguments = "Start-sleep -seconds 10",
                    RedirectStandardOutput = false,
                    UseShellExecute = true,
                    CreateNoWindow = true
                };
    
                var p = System.Diagnostics.Process.Start(processInfo);
    

    You can't redirect stdout, so if you need to get the results from the script, the easiest method would be build a temporary .ps1 script file and have it write to a log file which your C# code would then read.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.