Search code examples
c#vb.netcommand-lineelevated-privileges

Any way to programmatically get a value/setting from Bcdedit.exe, using .NET?


When running bcdedit.exe from an elevated command prompt, you can see the values of the current BCD settings. I need to read the setting/value of hypervisorlaunchtype.

Screenshot

Does anyone know a way to do this?

I've tried to write the piped output to a tmp file so that I could parse it, but ran into piped output issues due to the fact that bcdedit.exe needs to be run from an elevated prompt. Maybe there's a better way?

Edit: I forgot to add that I'd like to be able to do this without the end user seeing the Command Prompt at all (i.e. not even a quick flash) is possible.


Solution

  • First, run your Visual Studio as Administrator and try this code in a console application (run the application with debugging):

        static void Main(string[] args)
        {
    
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.FileName = @"CMD.EXE";
            p.StartInfo.Arguments = @"/C bcdedit";
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
    
            // parse the output
            var lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Where(l => l.Length > 24);
            foreach (var line in lines)
            {
                var key = line.Substring(0, 24).Replace(" ", string.Empty);
                var value = line.Substring(24).Replace(" ", string.Empty);
                Console.WriteLine(key + ":" + value);
            }
            Console.ReadLine();
        }
    

    However, there is a problem, If you want this to work when launching the application from outside the elevated Visual Studio, you need to configure your application to ask for elevated rights:

    On your project, click add new item and select Application Manifest File.

    Open app.manifest file and replace this line:

    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
    

    with this one:

    <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />