Skip to content

Error loading the wrong assembly with not elegant workaround #193

@JaimePalazuelosB

Description

@JaimePalazuelosB

Hi,

I am using this module for Azure Policies with Automanage. This is DSC based, and it runs both PowerShell and any modules on the policy's package in an isolated folder. Therefore, even if the machine does not have PowerShell 6 installed, it runs it using this version.

The module is working fine almost on every machine, but there are some where I am having an error in this section:

$parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.Parser")
$parser = $parserType::new($stringReader)

These machines are Windows 2019 Datacenter, but it is identifying them as Core, so it is loading the "netstandard2.1" assembly instead of "net47", causing an error "Get-Serializer: You cannot call a method on a null-valued expression".

Running the same code using PowerShell 5.1 installed on the machine does not cause any error, I guess because it does not detect the machine as Core.

I have temporarily implemente the following workaround:

function Invoke-LoadAssemblyOnError {
    $libDir = Join-Path $here "lib"
    $assemblies = @{
        "core"  = Join-Path $libDir "netstandard2.1"
        "net47" = Join-Path $libDir "net47"
    }

    return (Invoke-LoadFile -assemblyPath $assemblies["net47"])
}


function Get-YamlDocuments {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$Yaml,
        [switch]$UseMergingParser = $false
    )
    PROCESS {
        $stringReader = New-Object System.IO.StringReader($Yaml)
        try {
            $parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.Parser")
            $parser = $parserType::new($stringReader)
        }
        catch {
            $assemblies = Invoke-LoadAssemblyOnError

            $yamlDotNetAssembly = $assemblies["yaml"]
            $stringQuotedAssembly = $assemblies["quoted"]

            $parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.Parser")
            $parser = $parserType::new($stringReader)
        }

        if ($UseMergingParser) {
            $parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.MergingParser")
            $parser = $parserType::new($parser)
        }

        $yamlStream = $yamlDotNetAssembly.GetType("YamlDotNet.RepresentationModel.YamlStream")::new()
        $yamlStream.Load($parser)

        $stringReader.Close()

        return $yamlStream
    }
}

It is not an elegant solution, so I would rather to have an official and better resolution.

Thanks in advance.

Jaime

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions