Quantcast
Channel: TechNet Blogs
Viewing all articles
Browse latest Browse all 34890

Convert a code in C# to be used in PowerShell

$
0
0

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 2015ProjectsConvertCodeForPSConvertCodeForPSbinDebug
  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)WindowsPowerShellModulesimg3
  9. Open your PowerShell ISE now and load the module you just created:[System.Reflection.Assembly]::LoadFrom(“C:Program Files (x86)WindowsPowerShellModulesConvertCodeForPSConvertCodeForPS.dll”)img4
  10. We have then instantiated our class and called the respective functions we created in our tutorial.

 

Cheers 🙂

 


Viewing all articles
Browse latest Browse all 34890

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>