aClass.cs
aClass.cs
is the C# source file we want to create an assembly from. It defines a class (aptly named aClass
) within the namespace TQ84
. The class' constructor takes two values, an int
and a string
and prints these values to the console when printValues
is invoked on the object created by the constructor:
using System;
namespace TQ84 {
public class aClass {
private int num_;
private string txt_;
public aClass(int num, string txt) {
num_ = num;
txt_ = txt;
}
public void printValues() {
Console.WriteLine(String.Format("num = {0}, txt = {1}", num_, txt_));
}
}
}
Load the source code into the
variable $sourceCode
and then create the assembly:
$sourceCode = get-content -raw aClass.cs
$assemblyPath = "$pwd/anAssembly.dll"
if (test-path $assemblyPath) {
remove-item $assemblyPath
}
add-type `
-typeDefinition $sourceCode `
-outputAssembly $assemblyPath `
-outputType library
Use assembly in PowerShell
After creating the assembly, it can be used in the same or another PowerShell session like so:
$null = [System.Reflection.Assembly]::LoadFile("$pwd/anAssembly.dll")
$obj_1 = new-object TQ84.aClass 42, 'Hello world'
$obj_2 = new-object TQ84.aClass 99, 'Ninety-nine'
$obj_1.printValues()
$obj_2.printValues()
C-Sharp class that uses assembly
Here's another C# class. This class relies on the one that can be referenced in the created assembly:
using TQ84;
namespace XYZ {
public class useAssembly {
static public void run() {
aClass obj_1 = new TQ84.aClass(42, "Hello world");
aClass obj_2 = new TQ84.aClass(99, "ninety-nine");
obj_1.printValues();
obj_2.printValues();
}
}
}
Here,
add-type
is used to create a new type (to be used in the current PowerShell session) and to reference the required assembly (
anAssembly.dll
, that is):
$null = [System.Reflection.Assembly]::LoadFile("$pwd/anAssembly.dll")
add-type `
-typeDefinition (get-content -raw useAssembly.cs) `
-referencedAssemblies "$pwd/anAssembly.dll"
[XYZ.useAssembly]::run()
The following approach (without explicitly usind LoadFile
) did not work, it caused the error Exception calling "run" with "0" argument(s): "Could not load file or assembly:
add-type `
-typeDefinition (get-content -raw useAssembly.cs) `
-referencedAssemblies `
"$pwd/anAssembly.dll"
[XYZ.useAssembly]::run()