C# invoking Powershell, DLL could not be loaded

780 Views Asked by At

I am having a slightly odd problem.. the following lines run fine directly in powershell:

1) powercfg -AVAILABLESLEEPSTATES    
2) powercfg -energy

Straight forward enough, -energy generates its file, has other flags I could play with.

Running line 1 from C# works fine too (in any of the wonderful methods throughout this site, like

Powershell s_ps = PowerShell.Create();
s_ps.AddScript("powercfg -AVAILABLESLEEPSTATES");
Collection<PSObject> results = s_ps.Invoke();

(or the versions that run everything through a Pipeline, or create PSCommand(), and so on)

Running the same thing on the -energy works fine from the console, but if I try to call it through C# it starts talking about missing 'energy.dll' or one of its dependencies. All the dlls (including dependencies) are of course there - since it runs from command line, and verified manually anyway.

Visual Studio is running in Admin mode, and just to be on the safe side I built the ap and tried running that directly in Admin mode too

I have tried manually loading the dll

 s_ps.AddScript(@"[Reflection.Assembly]::LoadFrom('C:\Windows\System32\energy.dll') | Out-Null");

But it just throws an extra error saying it

'could not load file or assembly 'file:///C:\Windows\System32\energy.dll' or one of its dependencies'

Does anyone have any thoughts on what else would be causing issues? (Have to run for a bit, but if I find a solution before someone else I will of course post it, been hammering at it for most of the day though with no luck)

1

There are 1 best solutions below

0
On

As far as the -engery is a switch to the command it must understand as proper and execute it without asking for assembly. Only thing is since the powercfg.exe -energy uses async model execution the app needs to wait till 60secs to get the results. I tried executing as follows and worked.My env is Win 7 pro, i7,64bit

foreach (var v in PowerShellInterop.RunPowerShellScript("powercfg -energy"))
            Console.WriteLine(v);
    internal static IEnumerable RunPowerShellScript(string script)
    {
        PowerShell ps = PowerShell.Create();
        ps.AddScript(script);
        Collection<PSObject> result = ps.Invoke();
        foreach (PSObject obj in result)
        {
            yield return (obj);
        }
    }

Result

Enabling tracing for 60 seconds... Observing system behavior... Analyzing trace data... Analysis complete.

Energy efficiency problems were found.

5 Errors 19 Warnings 40 Informational

See {path}\Debug\energy-report.html for mor e details.