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.

  1. Open Visual Studio and create a new solution/project - Make sure you select the type as Class Library
  2. For this example, I have renamed the class to TestLibrary and defined two functions as follows:
  3. public string SayHello()
    return "Hello World";
    public string Echo(string value)
    return value;
  4. 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.
  5. Rebuild your solution to make sure everything is good and you have the binaries generated.
  6. Now browse to your project folder which would have a similar folder path: ...\visual studio 2015\Projects\ConvertCodeForPS\ConvertCodeForPS\bin\Debug
  7. Copy the contents of this folder and paste them in a new folder called ConvertCodeForPS
  8. Now, copy this folder into one of the PSModulePath defined folders like C:\Program Files (x86)\WindowsPowerShell\Modulesimg3
  9. 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")img4
  10. We have then instantiated our class and called the respective functions we created in our tutorial.


Cheers 🙂


Comments (3)

  1. Sonia Scott says:

    Great Post, it is especially useful when the author takes the time to spell out a solution in detail!

  2. David London says:

    Excellent article, very well written and too the point!

  3. JayPeeeeeee says:

    This comes in handy for me!

Skip to main content