1

Background

Using visual studio 2019 v16.10.3 I have created this (standard MS example source) class library and successfully compiled into MyMathLib.DLL

using System;

namespace MyMathLib
{
    public class Methods
    {
        public Methods()
        {
        }
        public static int Sum(int a, int b)
        {
            return a + b;
        }
        public int Product(int a, int b)
        {
            return a * b;
        }
    }
}

My MyMathLib.csproj file looks like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
</Project>

And then I want to try executing this code using powershell using the following script:

[string]$assemblyPath='S:\Sources\ResearchHans\DotNetFromPowerShell\MyMathLib\MyMathLib\bin\Debug\net5.0\MyMathLib.dll'
Add-Type -Path $assemblyPath

When I run this I get an error, and ask what's going on by querying the error for LoaderExceptions:

PS C:\WINDOWS\system32> S:\Sources\ResearchHans\DotNetFromPowerShell\TestDirectCSharpScript2.ps1
Add-Type : Kan een of meer van de gevraagde typen niet laden. Haal de LoaderExceptions-eigenschap op voor meer informatie.
At S:\Sources\ResearchHans\DotNetFromPowerShell\TestDirectCSharpScript2.ps1:2 char:1
+ Add-Type -Path $assemblyPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand
 

PS C:\WINDOWS\system32> $Error[0].Exception.LoaderExceptions
Kan bestand of assembly System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a of een van de afhankelijkhed
en hiervan niet laden. Het systeem kan het opgegeven bestand niet vinden.

PS C:\WINDOWS\system32> 

(Sorry for dutch windows messages: something like "Cannot load one or more of the types" and the loader exception Cannot load file or assembly "System.Runtime" etc...

I have seen many related issues on SO, but they are usually quite old and do not refer to .NET5.0

This works

When I directly compile the example source like below, it works just fine.

$code = @"
using System;

namespace MyNameSpace
{
    public class Responder
    {
        public static void StaticRespond()
        {
            Console.WriteLine("Static Response");
        }

        public void Respond()
        {
            Console.WriteLine("Instance Respond");
        }
    }
}
"@

# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
    Add-Type -TypeDefinition $code -Language CSharp;
}

[MyNameSpace.Responder]::StaticRespond();

$instance = New-Object MyNameSpace.Responder;
$instance.Respond();

Why?

The whole Idea to have a proof of concept that I can utilize my .NET5 libraries using e.g. powershell scripts. I actually have to load a much more complicated assembly, but this oversimplified example seems to be my primary issue at the moment.

The question

What am I missing? - How do I get this to work?

TIA for bearing with me.

1
  • Do you build your assembly on a x64 arch ? In which mode (x86_64 ? x64 only ?) ? Commented Jul 12, 2021 at 16:08

1 Answer 1

3

You didn't state what version of Powershell that you're using. However, I can reproduce the error by the following.

In VS 2019, create a Class Library (C# Windows Library).

enter image description here

Rename the class from "Class1.cs" to "Methods.cs"

Methods.cs

using System;

namespace MyMathLib
{
    public class Methods
    {
        public int Sum(int a, int b)
        {
            return a + b;
        }
        public int Product(int a, int b)
        {
            return a * b;
        }
    }
}

Compile.

  • Open Windows Powershell
  • Type: (Get-Host).version

enter image description here

Then type the following:

PS C:\Users\Test> [string]$assemblyPath="C:\Temp\MyMathLib.dll"
PS C:\Users\Test> Add-Type -Path $assemblyPath

which results in the following error:

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
At line:1 char:1
+ Add-Type -Path $assemblyPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand

This occurs because .NETCore 5 isn't supported by Windows Powershell 5.1 - only on versions 6 and above. For Powershell 5.1 or below, it's necessary to use .NETFramework instead.

See Resolving PowerShell module assembly dependency conflicts which states the following:

PowerShell and .NET ... In general, PowerShell 5.1 and below run on .NET Framework, while PowerShell 6 and above run on .NET Core. These two implementations of .NET load and handle assemblies differently.

See Installing PowerShell on Windows for how to get the latest version of Powershell.

In Powershell 7.1.3, one can call a method from MyMathLib.dll by doing the following:

PS C:\Users\Test> [string]$assemblyPath="C:\Temp\MyMathLib.dll"
PS C:\Users\Test> Add-Type -Path $assemblyPath
PS C:\Users\Test> $m1 = New-Object -TypeName MyMathLib.Methods
PS C:\Users\Test> $m1.Sum(2,3)

Note: Since the class/methods aren't static, it's necessary to create an instance by using $m1 = New-Object -TypeName MyMathLib.Methods

However, if it's static (as shown below):

MyMathLib.cs

using System;

namespace MyMathLib
{
    public static class Methods
    {
        public static int Sum(int a, int b)
        {
            return a + b;
        }
        public static int Product(int a, int b)
        {
            return a * b;
        }
    }
}

Then one can do the following in Powershell:

PS C:\Users\Test> [string]$assemblyPath="C:\Temp\MyMathLib.dll"
PS C:\Users\Test> Add-Type -Path $assemblyPath
PS C:\Users\Test> [MyMathLib.Methods]::Sum(3,2)
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed upgrading to powershell 7 did the trick. I Assumed Win10 auto - update gives me latest updates on Powershell too. Re-experiended that assumption is the mother of all f:ups. Thx!

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.