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.Automationinstead ofMicrosoft.PowerShell.Sdk, the error is different (PSSnapInException):Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly 'C:\Users\ZhouJie\.nuget\packages\System.Management.Automation\7.2.4\runtimes\win\lib\net6.0\Microsoft.PowerShell.Commands.Diagnostics.dll'. 系统找不到指定的文件。

-
Confirmed even using Visual Studio 2022, there is also same error for
System.Management.Automation, so there have to be a problem withinLINQPad 7andMicrosoft.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
AssemblyLoadContextand make it work again? Like this:HashSet<string> asmFullNames = Util.AssemblyLoadContext .Assemblies .Select(x => x.FullName) .ToHashSet(); foreach (Assembly asm in AssemblyLoadContext.Default.Assemblies) { if (!asmFullNames.Contains(asm.FullName)) { Util.AssemblyLoadContext.LoadFromAssemblyName(asm.GetName()); } } -
The problem is that the assemblies load into both ALCs. I've logged an issue here:
https://github.com/PowerShell/PowerShell/issues/17492
