2

I have a .NET 5 that uses the plugin capability, as specified here.

I've created a plugin that uses PowerShell (Microsoft.PowerShell.SDK nuget package (v7.1.4)).

Inside the plugin, I'm executing this code:

using (PowerShell ps = PowerShell.Create())
{
    ps.AddScript("Get-Disk");
    ps.Invoke();    
    
    Console.WriteLine(string.Join(", ", ps.Streams.Error));
}

The output I'm getting is:

The 'Get-Disk' command was found in the module 'Storage', but the module could not be loaded. For more information, run 'Import-Module Storage'.

So, I tried executing

using (PowerShell ps = PowerShell.Create())
{
    ps.AddScript("Import-Module Storage; Get-Disk");
    ps.Invoke();    
    
    Console.WriteLine(string.Join(", ", ps.Streams.Error));
}

And this is what I get:

One or more errors occurred. (The getter method should be public, not void, static, and have one parameter of the type PSObject.);The 'Get-Disk' command was found in the module 'Storage', but the module could not be loaded. For more information, run 'Import-Module Storage'.

What am I doing wrong? This code works perfectly if I invoke the code outside the loaded plugin.

EDIT

I've created a minimal reproducible example of the problem, you can see it here. The code is super simple. Be sure to compile every project before running it. Otherwise, the plugin won't be compiled and won't load from the main app.

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • 1
    That's curious, and it's a curious error. I tried with a pristine project (same versions), and it seems to work fine. I'm only half-joking: have you tried cleaning up the build artifacts and rebuilding from scratch? – mklement0 Sep 22 '21 at 21:06
  • 1
    @mklement0 OMG, I think it's related to the environment I was running. I ran it using LINQPad (using .NET 5, of course). I've created a console application from scratch and it worked, surprisingly. I had issues in the application I was migrating, too. I'll double check it tomorrow and come with more info. – SuperJMN Sep 22 '21 at 21:29
  • In some cases you may also need to set the execution policy to at least RemoteSigned in order to load the Storage module. Please see [this answer](https://stackoverflow.com/a/69052040/11954025) for an example of one way to do this – Daniel Sep 22 '21 at 22:50
  • I've updated the OP because it seems to be related to the plugin mechanism of .NET 3.1+. I've uploaded a minimal reproducible example. Please, take a look. Thanks! – SuperJMN Sep 23 '21 at 15:44
  • .NET Core 3.0+, to be exact – SuperJMN Sep 24 '21 at 14:07

0 Answers0