7

Can anyone help me to convert a C# .NET program to PowerShell cmdlet? I am very new to this area. Please help me to get out of this checkpoint!

Regards,

Arun

YetAnotherRandomUser
  • 1,320
  • 3
  • 13
  • 31
Arun
  • 580
  • 6
  • 11
  • 17
  • Possible duplicate of [Methods to convert C# code to a PowerShell Script?](http://stackoverflow.com/questions/2143460/methods-to-convert-c-sharp-code-to-a-powershell-script) – Michael Freidgeim Apr 11 '16 at 22:36

3 Answers3

13

Add a reference to System.Management.Automation, create a class that inherits from Cmdlet and override the ProcessRecord method:

[Cmdlet(VerbsCommon.Get, "Double")]
public class GetDouble : Cmdlet
{
    [Parameter]
    public int SomeInput { get; set; }

    protected override void ProcessRecord()
    {
        WriteObject(SomeInput * 2);
    }
}

Add an installer:

[RunInstaller(true)]
public class MySnapin : PSSnapIn
{
    public override string Name { get { return "MyCommandlets"; } }
    public override string Vendor { get { return "MyCompany"; } }
    public override string Description { get { return "Does unnecessary aritmetic."; } }
}

Install your commandlet assembly:

Installutil /i myassembly.dll

And add:

Add-PsSnapin MyCommandlets
Cristian Libardo
  • 9,260
  • 3
  • 35
  • 41
2

First of all, you should convert your .cs file into a DLL using PowerShell template. Then by using pssnapin and getproc you can convert it into a DLL.

YetAnotherRandomUser
  • 1,320
  • 3
  • 13
  • 31
user45618
  • 21
  • 2
2

There's an add-on for Reflector to do that. Here's a good article with the example: http://msmvps.com/blogs/paulomorgado/archive/2009/09/18/powershell-for-the-net-developer.aspx*

.NET Reflector has an array of add-ons on CodePlex, and one of these is the PowerShell add-on that allows you to disassemble code directly into PowerShell.

In this example, I am opening the method ChangeAccountPassword from the SPUtility library in SharePoint:

image

I can now change targets from C# to PowerShell.

image

When you need to convert helper methods from C# to PowerShell or if you’re new to PowerShell syntax, this tool is really helpful!

[*] The link is dead as of 10/12/2015.

Nikita R.
  • 7,245
  • 3
  • 51
  • 62