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.
Hello, That’s an interesting article. However, I am trying to refer to constants in installed C# DLLs from a PowerShell script. I do not want to include the C# source code in the PowerShell script. Is this possible? Many thanks. -Keith
Hi Keith,
The C# code in the article is just to show the functionality of the dll.
The dll’s can be referred inside the PS code using the dll file path
#Referring the dll in the script
Add-Type -Path “C:\PowerShell\custlib.dll”
#To access an object in the dll, Create object of CustomClass which is defined in the DLL, create new object of the class
$custObj = New-Object CustomNamespace.CustomClass
#Access the variable using the new object $custObj
$custObj.variablename
Hope this is what you are looking for.
Hello, thanks for your helpful reply re: Add-Type. Have a good day. 🙂