azurepowershell.net-coredlladd-type

Load .NET Core dlls in Powershell Script, issues with loading


I have some issues while loading dlls in a PowerShell script:

# PowerShell
param(
    [string]$Name
)

#Download the DLL
$testClassPath = "$env:TEMP\TestClassLibrary.dll";
$assemblyUrlPath = "https://some.url/TestClassLibrary.dll";

try {
    $webClient = New-Object System.Net.WebClient;
    $webClient.DownloadFile($assemblyUrlPath, $testClassPath);
    $webClient.Dispose();
}
catch [System.Exception] {
}

if (Test-Path $testClassPath) {
    Write-Output "Dlls exists."
    #install package?
    #dotnet add package Azure.Storage.Blobs;
    #Try to Create an instance of the class from the DLL
    try {
        Add-Type -Path $testClassPath -PassThru

        # Create an instance of TestProcessFile with the fileName argument
        $testProcessFile = New-Object TestClassLibrary.TestProcessFile $Name

        # Call the async method ProcessAsync and wait for it to complete
        $task = $testProcessFile.ProcessAsync()
        $task.Wait()
    } catch [System.Reflection.ReflectionTypeLoadException] {
        Write-Host "Message: $($_.Exception.Message)"
        Write-Host "StackTrace: $($_.Exception.StackTrace)"
        Write-Host "LoaderExceptions: $($_.Exception.LoaderExceptions)"
    }
} else {
    Write-Output "File does not exist."
}

This code downloads a business dll, TestClassLibrary.dll is a .NET Core 8 library which uses Azure.Storage and Azure.Storage.Blobs.

I tried using $webClient to download those and load them using Add-Type as well, but I get errors.

I also tried using dotnet add package Azure.Storage.Blobs;

Any ideas?


Solution

  • Refer the blog to achieve your requirement of accessing .NET Core dll assembly files in PowerShell Script.

    You can also use below sample script to load the .NET assembly dlls in PowerShell script.

    script.ps1:

    # Set path to the DLL folder
    $assemblyDir = "C:\AzureBlobsSDK"
    
    # Unblock DLLs once 
    Get-ChildItem -Path $assemblyDir -Filter *.dll | Unblock-File
    
    # PowerShell assembly resolver function
    function Resolve-Assembly {
        param (
            [object]$sender,
            [System.ResolveEventArgs]$args
        )
    
        $baseDir = $assemblyDir
        $fileName = [System.Reflection.AssemblyName]::new($args.Name).Name + ".dll"
        $path = Join-Path $baseDir $fileName
    
        if (Test-Path $path) {
            return [System.Reflection.Assembly]::LoadFrom($path)
        }
        return $null
    }
    
    # Create a ResolveEventHandler delegate pointing to the resolver function
    $handler = [System.ResolveEventHandler]{
        param($sender, $args)
        Resolve-Assembly -sender $sender -args $args
    }
    
    # Register the assembly resolver handler
    [System.AppDomain]::CurrentDomain.add_AssemblyResolve($handler)
    
    $requiredDlls = @(
        "Azure.Core.dll",
        "Azure.Storage.Blobs.dll",
        "System.Buffers.dll",
        "System.Memory.dll",
        "System.Diagnostics.DiagnosticSource.dll",
        "System.Threading.Tasks.Extensions.dll",
        "Microsoft.Bcl.AsyncInterfaces.dll"  
    )
    
    # Loading all the required DLLs explicitly
    foreach ($dll in $requiredDlls) {
        $fullPath = Join-Path $assemblyDir $dll
        if (Test-Path $fullPath) {
            Write-Host "Loading $dll"
            [System.Reflection.Assembly]::LoadFrom($fullPath) | Out-Null
        } else {
            Write-Error "Missing DLL: $dll"
            exit 1
        }
    }
    
    $connectionString = "<Storage_Connection_String>"
    
    $blobServiceClientType = [Azure.Storage.Blobs.BlobServiceClient]
    
    # Creating a client instance using the connection string constructor
    $client = [Activator]::CreateInstance($blobServiceClientType, $connectionString)
    
    if ($null -ne $client) {
        Write-Host "Successfully created BlobServiceClient instance."
    } else {
        Write-Error "Failed to create BlobServiceClient instance."
    }
    
    PS C:\psfunc> .\main.ps1
        
    Loading Azure.Core.dll
    Loading Azure.Storage.Blobs.dll
    Loading System.Buffers.dll
    Loading System.Memory.dll
    Loading System.Diagnostics.DiagnosticSource.dll
    Loading System.Threading.Tasks.Extensions.dll
    Loading Microsoft.Bcl.AsyncInterfaces.dll
    Successfully created BlobServiceClient instance