35

I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script. How could I automate this process?

While I am aware that there are methods that can convert a .cs file to a cmdlet, I'm only interested in converting the C# code to a script or module.

Community
  • 1
  • 1
Tangiest
  • 43,737
  • 24
  • 82
  • 113
  • here's a paid product https://docs.poshtools.com/powershell-tools-documentation/visual-studio/code-conversion – BozoJoe Feb 21 '22 at 15:58

3 Answers3

79

I know you're looking for something that somehow converts C# directly to PowerShell, but I thought this is close enough to suggest it.

In PS v1 you can use a compiled .NET DLL:

PS> $client = new-object System.Net.Sockets.TcpClient
PS> $client.Connect($address, $port)

In PS v2 you can add C# code directly into PowerShell and use it without 'converting' using Add-Type (copied straight from MSDN )

C:\PS>$source = @"
public class BasicTest
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

    public int Multiply(int a, int b)
    {
        return (a * b);
    }
}
"@

C:\PS> Add-Type -TypeDefinition $source

C:\PS> [BasicTest]::Add(4, 3)

C:\PS> $basicTestObject = New-Object BasicTest 
C:\PS> $basicTestObject.Multiply(5, 2)
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
James Pogran
  • 4,279
  • 2
  • 31
  • 23
  • 1
    Can I use my custom libraries C# with helpers and utils class? – Kiquenet Mar 05 '13 at 15:38
  • How to get .Netframework support in PowerShell? Will this work on just a brand new machine imaged with windows without .netframework installed? How to get .net framework support in a powershell? – Venkatesh Muniyandi Feb 21 '19 at 00:30
12

There is a Reflector add-in for PowerShell that will allow you to see the corresponding PowerShell script for static methods on classes

There's a good post with the example: http://blogs.msmvps.com/paulomorgado/2009/09/17/powershell-for-the-net-developer/.

Community
  • 1
  • 1
Tangiest
  • 43,737
  • 24
  • 82
  • 113
1

PowerShell Pro Tools for Visual Studio have a feature to convert C# code in a PowerShell script.

marsze
  • 15,079
  • 5
  • 45
  • 61