In the previous, we saw how to embed C# code in the PowerShell script. This article is about accessing the dll assembly files in PowerShell

Call dll assembly in PowerShell

Suppose the below C# code is compiled to a dll file custlib.dll, we can add the assembly to PowerShell.

using System;
namespace CustomNamespace
{
    public class CustomClass
    {
        //Function to Split the string
        public string[] Split(string value, char delimiter)
        {
            string[] strArray = value.Split(delimiter);
            return strArray;
        }

        //Function to sort
        public string[] Sorts(string[] strArray)
        {
            Array.Sort(strArray);
            return strArray;
        }
    }
}

Accessing dll in PowerShell

Load assembly Using Add-Type cmdlet

Add-Type -Path "C:\PowerShell\custlib.dll"

#Create object of CustomClass
$custObj = New-Object CustomNamespace.CustomClass

#Calling Split function
$custObj.Split("one,two,three",",")

#Calling Sort function
$custObj.Sorts(@("c","a","b"))

Load assembly using .Net Reflection class Load method

$AssemblyPath = "C:\PowerShell\custlib.dll"

#The dll file has to read as byte string
#The below cmdlet Get-Content with parameter -AsByteStream will only work in PowerShell version 6 and above.
#So .Net class System.IO.File can be used to read the file as byte stream
#$byteValues = Get-Content $AssemblyPath -AsByteStream -Raw

$byteValues = [System.IO.File]::ReadAllBytes($AssemblyPath)
[System.Reflection.Assembly]::Load($byteValues)


#Create object of CustomClass
$custObj = New-Object CustomNamespace.CustomClass

#Calling Split function
$custObj.Split("one,two,three",",")

#Calling Sort function
$custObj.Sorts(@("c","a","b"))

Compiling C# files to dll

CSharp code can be compiled to dll files using csc command line compiler.

One-liner to compile the C# to dll using PowerShell

Save the C# source code to custlib.cs to any folder

&"$env:windir\Microsoft.NET\Framework\v4.0.30319/csc" /target:library C:\PowerShell\custlib.cs 

Running the above line will generate the dll file.

Reference taken from https://gallery.technet.microsoft.com/scriptcenter/c66c2a00-8a24-4412-aa00-c18bda570508

Hope this is helpful and thank you for reading.