PowerShell CmdLet with NET8 could not load file or assembly

173 views Asked by At

I'm trying an experiment and I want to create a CmdLet for PowerShell in NET8. I have created a new Class Library and added the following packages:

  • Microsoft.PowerShell.SDK
  • PowerShellStandard.Library

as suggested in this post. Then, I added this code to create the CmdLet:

using System.Management.Automation;

namespace PowerShellCmdLet
{
    [Cmdlet("Get", "Test")]
    public class TestClass : Cmdlet
    {
        protected override void BeginProcessing()
        {
            Console.WriteLine("BeginProcessing");
        }
    }
}

When I open PowerShell on the project bin directory, I import my dll with

Import-Module .\PowerShellCmdLet.dll

but then I get this error:

Import-Module : Could not load file or assembly 'System.Management.Automation, Version=7.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. At line:1 char:1 Import-Module .\PowerShellCmdLet.dll

CategoryInfo          : NotSpecified: (:) [Import-Module], FileNotFoundException
FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand

I tried to open PowerShell as an administrator but I get the same issue.

1

There are 1 answers

0
M.Hassan On

i used the package: System.Management.Automation" Version="7.4.1" to build the dll.

<ItemGroup>
  <PackageReference Include="System.Management.Automation" Version="7.4.1" />
</ItemGroup>

Then using pwsh v 7.4.1, i can load the dll successfully and run the command

Import-Module path/to/PowerShellCmdLet.dll
#call the command
Get-Test

output:

BeginProcessing

Poweshell ISE can not load the dll because it does not support net8

If you are using VS code, you can run it, because vs code use pwsh if it is installed.