How to convert C# code to a PowerShell Script?

前端 未结 4 506
滥情空心
滥情空心 2020-12-13 00:43

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

相关标签:
4条回答
  • 2020-12-13 01:10

    Adam Discroll has created a Roslyn-based converter, and he even provides an online code converter - it seems to work for simple scripts, but has problems with i.e. static members or classes.

    0 讨论(0)
  • 2020-12-13 01:11

    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)
    
    0 讨论(0)
  • 2020-12-13 01:14

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

    0 讨论(0)
  • 2020-12-13 01:24

    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/.

    0 讨论(0)
提交回复
热议问题