Have a piece of code working in C# and want to use the same in PowerShell? Well, no problem!
Open Visual Studio, create a class library, compile it and when you reference your dll in PowerShell – you’re all set. So, lets see how we can do this step by step.
- Open Visual Studio and create a new solution/project – Make sure you select the type as Class Library
- For this example, I have renamed the class to TestLibrary and defined two functions as follows:
- public string SayHello()
{
return “Hello World”;
}
public string Echo(string value)
{
return value;
} - Please note that at this point, you might also want to add any Nuget packages to your code in case you are referring to them in your code.
- Rebuild your solution to make sure everything is good and you have the binaries generated.
- Now browse to your project folder which would have a similar folder path: …visual studio 2015ProjectsConvertCodeForPSConvertCodeForPSbinDebug
- Copy the contents of this folder and paste them in a new folder called ConvertCodeForPS
- Now, copy this folder into one of the PSModulePath defined folders like C:Program Files (x86)WindowsPowerShellModules
- Open your PowerShell ISE now and load the module you just created:[System.Reflection.Assembly]::LoadFrom(“C:Program Files (x86)WindowsPowerShellModulesConvertCodeForPSConvertCodeForPS.dll”)
- We have then instantiated our class and called the respective functions we created in our tutorial.
Cheers