Many know that you can use .Net-classes in Powershell directly.
These are then compiled into terms. But what many do not know is that it is also possible to use “pure” .Net code in Powershell. – It works like this:
Index
Compile C# Code in PowerShell and directly use it
In this article I want to show you, how to use .Net code and DLLs in PowerShell.
I want to start with the compilation of .Net Code in PowerShell:
1 2 3 4 5 6 7 8 9 |
Add-Type -TypeDefinition @" using System; using System.IO; public class Permissions { public static System.Collections.Hashtable GetPermissions(string path) { } } "@ |
The code will be compiled at the beginning of the script and written to memory. After that you can use it like a normal .Net class:
1 |
$permissions = [Permissions]::GetPermissions($path) |
Important: Please note that there are no global variables available, that you defined in the PowerShell part of the script. Additionally, “Add-Type” must be at the very beginning of the script.
Benefits of .Net Code in PowerShell
There are various advantages using this technique.
On one hand, .Net Code is faster that pure Powershell-cmdlets in many cases. Especially when it comes to file-system-operations.
On the other hand, you might already have some .Net Code you want to use and don’t want to “translate” it to PowerShell.
Integrate existing DLLs in Powershell
You can integrate existing .Net Code and use it now, but there is also a possibility to integrate DLLs directly.
To be able to use the functions of a DLL, proceed as follows:
1 2 3 4 5 6 |
$assembly = [Reflection.Assembly]::LoadFile("c:\path\file.dll") $instance = New-Object Class.Of.Assembly $instance.Property1 = $variable1 $instance.Property2 = $variable2 $instance.Property3 = $variable3 $result = $instance.function() |
I hope this helps you as much as it already helped me.
1 Comment
Leave your reply.