LINQPad7 unable import Powershell Hyper-V module to execute script
Let's say this code:
string _scr = ("Get-VM"); var _ps = PowerShell.Create(); _ps.AddScript(_scr); Collection<PSObject> _cObj = _ps.Invoke(); if (_ps.HadErrors) { Console.WriteLine(_ps.Streams.Error[0].ToString()); } foreach (PSObject _vm in _cObj) { Console.WriteLine(_vm); }
Is able to run in Visual Studio 2022 .NET Core 6.0 project (Install NuGet: Microsoft.PowerShell.SDK
):
Also able to run in LINQPad 5(By reference another assembly(install NuGet: Microsoft.PowerShell.5.1.ReferenceAssemblies
):
But confirmed unable to run in my latest LINQPad 7.4.2:(Install NuGet: Microsoft.PowerShell.SDK
)
After investigation, this seems related to Import-Module
, if we don't import any module, code will execute perfectly fine in LINQPad 7:
But code still unable to run in LINQPad 7 even if we write Import-Module Hyper-V
.
Comments
@JoeAlbahari Confirmed that old LINQPad6 also does not support Microsoft.Powershell.SDK:
If we reference to NuGet package:
System.Management.Automation
instead ofMicrosoft.PowerShell.Sdk
, the error is different (PSSnapInException):Confirmed even using Visual Studio 2022, there is also same error for
System.Management.Automation
, so there have to be a problem withinLINQPad 7
andMicrosoft.PowerShell.SDK
:The only workaround I can use, is calling powershell exe, @JoeAlbahari I think this one you can take a look in LINQPad side.
That library appears to load assemblies directly into the default ALC. This makes it incompatible with LINQPad - or any program that runs in a non-default ALC.
@JoeAlbahari Thank you pointing out the direction, just wondering is it possible to find a workaround and load these assemblies into non-default
AssemblyLoadContext
and make it work again? Like this:The problem is that the assemblies load into both ALCs. I've logged an issue here:
https://github.com/PowerShell/PowerShell/issues/17492