简体   繁体   English

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

[英]How to convert C# code to a PowerShell Script?

I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script.我经常需要将现有的 C# 代码片段/.CS 文件转换为 PowerShell 脚本。 How could I automate this process?我怎样才能自动化这个过程?

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

I know you're looking for something that somehow converts C# directly to PowerShell, but I thought this is close enough to suggest it.我知道您正在寻找以某种方式将 C# 直接转换为 PowerShell 的东西,但我认为这足以建议它。

In PS v1 you can use a compiled .NET DLL:在 PS v1 中,您可以使用已编译的 .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 )在 PS v2 中,您可以将 C# 代码直接添加到 PowerShell 中,并使用 Add-Type(直接从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)

There is a Reflector add-in for PowerShell that will allow you to see the corresponding PowerShell script for static methods on classes有一个用于 PowerShellReflector 插件,可让您查看类上静态方法的相应 PowerShell 脚本

There's a good post with the example: http://blogs.msmvps.com/paulomorgado/2009/09/17/powershell-for-the-net-developer/ .有一个很好的例子: http : //blogs.msmvps.com/paulomorgado/2009/09/17/powershell-for-the-net-developer/

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM