Convert a code in C# to be used in PowerShell
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 2015\Projects\ConvertCodeForPS\ConvertCodeForPS\bin\Debug
- 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)\WindowsPowerShell\Modules
- Open your PowerShell ISE now and load the module you just created:[System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\WindowsPowerShell\Modules\ConvertCodeForPS\ConvertCodeForPS.dll")
- We have then instantiated our class and called the respective functions we created in our tutorial.
Cheers :)
Comments
- Anonymous
January 25, 2017
Great Post, it is especially useful when the author takes the time to spell out a solution in detail! - Anonymous
February 01, 2017
Excellent article, very well written and too the point! - Anonymous
February 03, 2017
This comes in handy for me!