Search code examples
c#powershellcmdpowercfg

Error when trying to run powercfg /srumutil through C# Process.Start()


I am trying to run the command powercfg /srumutil /output C:\\EnergyConsumption\\srumutil.csv /csv through a C# application. The command above runs successfully in powershell and cmd but it returns the following error when executed through my C# program:

Unable to perform operation. An unexpected error (0x1f) has occured: A device attached to the system is not functioning.

I will clarify that:

  • I am running this command on a machine with battery (laptop) in both cases.
  • Visual studio is running as administrator and process is started with Verb = "runas" so it should be elevated as well.
  • I have tried every variation of this in C# including (all these failed):
    • cmd.exe /K powercfg /srumutil
    • powershell.exe Start-Process powercfg /srumutil
    • putting it in a bat file and running the bat file with Process.Start().
  • Other arguments will work with Process.Start and powercfg like powercfg /L but never /srumutil

The code in question:

using System;
using System.Diagnostics;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var info = new ProcessStartInfo()
            {
                FileName = "powercfg.exe",
                Arguments = "/srumutil /output C:\\EnergyConsumption\\srumutil.csv /csv",
                Verb = "runas",
                UseShellExecute = false
            };

            var proc = Process.Start(info);
            proc.WaitForExit();
            Console.ReadLine();
        }
    }
}

Long story short powercfg /srumutil works as intended everywhere except through Process.Start() function. Is there something I am missing here?


Solution

  • I think your code is fine and the issue is in the execution context as you suspected. I get the same error when trying to run powercfg /srumutil in non-elevated PowerShell session, while it works fine in elevated which points into lack of admin rights. But, in this case, the error message might be misleading. I also get the same error when running the code in x86 process, instead of x64 - both in PowerShell and C#. Try to check if your application is x86 or x64 and compare that to the PowerShell process in which you test that powercfg /srumutil runs fine.