Assemblies that were loaded into a
PowerShell cannot be unloaded anymore and consequenctly, there is no
remove-type
cmdLet. There is no other way to get rid of such assemblies from memory but to restart PowerShell.
Adding a DLL to a PowerShell session
The following simple example tries to demonstrate how a
DLL can be added to
PowerShell session.
First, we need to create a
DLL. We create it from the following source code
namespace TQ84 {
public class T {
public static int twice(int a) {
return 2*a;
}
}
}
This source is compiled into a DLL with
csc.exe
, the
C# compiler:
PS C:\path\to\somewhere> csc -nologo -target:library .\tq84_type.cs
The DLL can now be added to the current PowerShell session with the
add-type
cmdLet:
PS C:\path\to\somewhere> add-type -path 'tq84_type.dll'
We verify if the DLL was actually loaded. The following statement reports it as being loaded:
PS C:\path\to\somewhere> [AppDomain]::CurrentDomain.GetAssemblies()
Now that the DLL is loaded, we can use its functionality. Static methods can be invoked without creating an object:
PS C:\path\to\somewhere> [TQ84.T]::twice(21)
42
In order to invoke member methods, an instance of the class needs to be created. This can be done with
new-object '….dll'
Option -typedef to add a class from C-Sharp
With the
-typedef
parameter,
add-type
can be given
C# source code(!) to compile.
add-type
will then add the result to the current session:
add-Type -typedef @'
using System;
public class inl {
public DateTime whenCreated;
public inl() { whenCreated = DateTime.Now; }
}
'@
$inl = new-object inl
start-sleep -s 3
write-output "It's $([DateTime]::Now) now, `$inl was created at $($inl.whenCreated)."
Adding a WinAPI function
The following snippet creates a type with a
WinAPI function so that it can be called from PowerShell.
set-strictMode -version latest
$newType = add-type -name user32 -passThru -memberDefinition '
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern Int32 MessageBox(
IntPtr hWnd,
String text,
String caption,
int options
);'
$MB_OKCANCEL = 4
$ID_YES = 6
$ID_NO = 7
$chosen = $newType::MessageBox(0, 'Should I?', 'Important question', $MB_OKCANCEL)
if ($chosen -eq $ID_YES) {
write-host 'Yeah!'
}
elseif ($chosen -eq $ID_NO) {
write-host 'Nay!'
}
else {
write-host 'This is quite an unexpected answer.'
}
When executed, a simple yes-no Message Box is shown: