Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Import assemblies for C# embedded in PowerShell

You can import assemblies (.NET DLLs) in PowerShell like this:

[void][reflection.assembly]::LoadWithPartialName("System.Drawing")
New-Object System.Drawing.Drawing2D.GraphicsPath

But you will get an error when you tring to use these assemblies in C# source embedded in PowerShell script. Assemblies loaded with LoadWithPartialName aren't referenced from embedded source.

[void][reflection.assembly]::LoadWithPartialName("System.Drawing")
Add-Type @"
using System.Drawing.Drawing2D;
"@
Add-Type : c:\tmp\_System\ama4povk.0.cs(1) : The type or namespace name 'Drawing2D' could not be found (are you missing a using directive or an assembly reference?)
c:\tmp\_System\ama4povk.0.cs(1) : >>> using System.Drawing.Drawing2D;
At line:1 char:1
+ Add-Type @"
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception
    + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Add-Type : Cannot add type. Compilation errors occurred.
At line:1 char:1
+ Add-Type @"
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
    + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

With Add-Type, you have to specify assemblies with -ReferencedAssemblies option like this:

Add-Type -ReferencedAssemblies ("System.Drawing") @"
using System.Drawing.Drawing2D;
"@