如何将C#代码转换为PowerShell脚本?

如何将C#代码转换为PowerShell脚本?

问题描述:

我通常必须将现有的C#代码段/.CS文件转换为PowerShell脚本。我该如何自动化该过程?

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

虽然我知道有些方法可以将.cs文件转换为cmdlet ,我只对将C#代码转换为脚本或模块感兴趣。

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.

我知道您正在寻找某种可以将C#直接转换为PowerShell的东西,但是我认为这足够接近

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

在PS v1中,您可以使用已编译的.NET DLL:

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

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

在PS v2中,您可以将C#代码直接添加到PowerShell,并使用它而无需使用添加类型(直接从 MSDN a>)

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)