33

我经常需要将现有的 C# 代码片段/.CS 文件转换为 PowerShell 脚本。我怎样才能使这个过程自动化?

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

4

4 回答 4

75

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)
于 2010-01-27T01:20:55.133 回答
12

PowerShell有一个Reflector 插件,可让您查看类上静态方法的相应 PowerShell 脚本

这个例子有一篇很好的帖子:http: //blogs.msmvps.com/paulomorgado/2009/09/17/powershell-for-the-net-developer/

于 2010-01-26T23:35:06.523 回答
1

适用于 Visual Studio 的PowerShell Pro Tools具有在 PowerShell 脚本中转换 C# 代码的功能。

于 2020-09-29T15:04:56.987 回答
-2

Adam Discroll创建了一个基于 Roslyn 的转换器,他甚至还提供了一个在线代码转换器- 它似乎适用于简单的脚本,但在静态成员或类方面存在问题。

于 2017-07-13T15:09:12.827 回答