Loading C# DLL with powershell, [System.Type]::GetType returns null

Multi tool use


Loading C# DLL with powershell, [System.Type]::GetType returns null
I have a simple DotNet DLL like this
namespace ClassLibrary1
{
public class Class1
{
public static void Test()
{
Process.Start("CMD.exe", "/C calc");
}
}
}
When I try to load this DLL with powershell
$Path = "c:\test\ClassLibrary1.dll";
$Namespace = "ClassLibrary1";
$ClassName = "Class1";
$Method = "Test";
$Arguments = $null
$Full_Path = [System.IO.Path]::GetFullPath($Path);
$AssemblyName = [System.Reflection.AssemblyName]::GetAssemblyName($Full_Path)
$Full_Class_Name = "$Namespace.$ClassName"
$Type_Name = "$Full_Class_Name, $($AssemblyName.FullName)"
$Type = [System.Type]::GetType($Type_Name)
$MethodInfo = $Type.GetMethod($Method)
$MethodInfo.Invoke($null, $Arguments)
It does not work, because [System.Type]::GetType($Type_Name)
returned $null
[System.Type]::GetType($Type_Name)
$null
Any ideas?
[System.Type]::GetType
You may need to use
LoadFile
as per this: stackoverflow.com/questions/3079346/…– Subbu
13 hours ago
LoadFile
1 Answer
1
Use Add-Type -Path
to load your assembly.
Add-Type -Path
After loading, to get a reference to that assembly's [ClassLibrary1.Class1]
type as a [Type]
for reflection via a string variable, simply cast the latter to [Type]
.
[ClassLibrary1.Class1]
[Type]
[Type]
The following fixed, annotated version of your code demonstrates the approach:
# Compile the C# source code to assembly .ClassLibrary1.dll
Add-Type -TypeDefinition @'
namespace ClassLibrary1
{
public class Class1
{
public static void Test()
{
System.Diagnostics.Process.Start("CMD.exe", "/C calc");
}
}
}
'@ -OutputAssembly .ClassLibrary1.dll
# Define the path to the assembly. Do NOT use "\" as the path separator.
# PowerShell doesn't use "" as the escape character.
$Path = ".ClassLibrary1.dll"
$Namespace = "ClassLibrary1"
$ClassName = "Class1"
$Method = "Test"
$Arguments = $null
# Load the assembly by its filesystem path, using the Add-Type cmdlet.
# Use of relative paths works.
Add-Type -Path $Path
$Full_Class_Name = "$Namespace.$ClassName"
# To get type [ClassLibrary1.Class1] by its full name as a string,
# simply cast to [type]
$Type = [type] $Full_Class_Name
$MethodInfo = $Type.GetMethod($Method)
$MethodInfo.Invoke($null, $Arguments)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You are not loading assembly.
[System.Type]::GetType
does not load assembly unless it is in GAC or assembly search path.– PetSerAl
14 hours ago