0

I'm trying to use the Get-VM Cmdlet called from C# on a Hyper-V host.

Obviously, the according PowerShell module Hyper-V has to be imported first. The import fails, however - apparently because the module is supported only on PowerShell 3.0 (at least that's what I figure from this article). The PowerShell used by System.Management.Automation seems to be version 2.0, though.

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "Hyper-V" });
Runspace runSpace = RunspaceFactory.CreateRunspace(iss);
runSpace.Open();
foreach (var err in (ArrayList)runSpace
        .SessionStateProxy.PSVariable.GetValue("Error"))
    Console.WriteLine(err.ToString());
runSpace.Close();

returns

The 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Hyper-V\Hyper-V.psd1' module cannot be imported because its manifest contains one or more members that are not valid. The valid manifest members are ('ModuleToProcess', ...). Remove the members that are not valid ('HelpInfoUri'), then try to import the module again.

Is there a way to use a specific version of PowerShell in C#?

2 Answers 2

3

A colleague figured it out:

Apparently, .NET 4+ comes with an all new common language runtime: the CLR4
This runtime uses its own assemblies loaded from a new assembly cache located at C:\Windows\Microsoft.NET\assembly.

The System.Management.Automation version 3.0.0.0, which will automatically use PowerShell 3.0, exists for the CLR4 only. Because I configured my application to run under .NET 3.5, it would use the old CLR2 and could not even see the newer assembly.

To make sure the application would still run on .NET 3.5, add this to the App.config file in the project folder:

<supportedRuntime version="v4.0"/> 
<supportedRuntime version="v2.0.50727"/>


If CLR4 is available, it'll load the according GAC, find a policy file that redirects all references to System.Management.Automation version 1.0.0.0 to version 3.0.0.0 and the PowerShell-Modules work as expected.
If you only have .NET 3.5, the older version will be loaded; PowerShell still works, but only up to version 2.0.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you looked at this yet?

http://code.msdn.microsoft.com/windowsdesktop/Windows-PowerShell-30-SDK-9a34641d

You might just need the new SDK to call Powershell 3 even if PSv3 is installed on your system already, but I'm usually just a straight Powershell guy.

1 Comment

This probably would have worked, but I need my application to run on .NET 3.5 as well - I could not reference to the 3.0.0.0 assembly directly, since it is .NET 4+ Still +1 for the hint in the right direction, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.