views:

308

answers:

2

Hi,

I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script. Can anyone offer any tools or methods that would allow some automation of this?

Note, 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.

Thanks, MagicAndi

+2  A: 

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

MagicAndi
+7  A: 

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

In PS v1 you can used 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)
James Pogran
James, I was hoping for a translation tool, but your answer is just as good!! +1
MagicAndi
James, accepted as the answer.
MagicAndi