且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-07 23:21:28

我知道您正在寻找某种可以将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)