Add-Type fails to compile C# source with references to NLog types

Viewed 102

I am trying to add a type in PowerShell v5 using C# source that references the NLog v5.0.0 logging library.

When I execute the following MRE:

$source = @'
namespace Test
{
    using System;

    public class MyClass
    {
        private NLog.ILogger logger;

        public static void Run()
        {
            Console.WriteLine("Hello world!");
        }
    }
}
'@

$path = 'C:\nlog\net46\NLog.dll'
$assemblies = @($path)

Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -Language CSharpVersion3 -ErrorAction Stop

[Test.MyClass]::Run()

I get the following error:

Add-Type : (0) : Warning as Error: Reference to type 'System.Action' claims it is defined in 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.dll', but it could not be found
(1) : namespace Test
At C:\test.ps1:21 char:1
+ Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -L ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception
    + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

If I comment out the field in the class that references the nlog type (private NLog.ILogger logger;), the MRE executes successfully.

The original code with the field left in compiles and executes if Add-Type is executed as follows:

Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -IgnoreWarnings -ErrorAction Stop

However, that is not sufficient to actually use the library. The following MRE fails differently:

$source = @'
namespace Test
{
    using System;

    public class MyClass
    {
        public static void Run()
        {
            Console.WriteLine(typeof(NLog.ILogger));
        }
    }
}
'@

$path = 'C:\nlog\net46\NLog.dll'
$assemblies = @($path)

Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -ErrorAction Stop

[Test.MyClass]::Run()

I now get the following error:

Exception calling "Run" with "0" argument(s): "Could not load file or assembly 'NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c' or one of its dependencies. The 
system cannot find the file specified."
At C:\test.ps1.ps1:21 char:1
+ [Test.MyClass]::Run()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException
0 Answers
Related