如何将 C# 代码转换为 PowerShell 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2143460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert C# code to a PowerShell Script?
提问by MagicAndi
I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script. How could I automate this process?
我经常需要将现有的 C# 代码片段/.CS 文件转换为 PowerShell 脚本。我怎样才能自动化这个过程?
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# 代码转换为脚本或模块感兴趣。
采纳答案by James Pogran
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)
回答by MagicAndi
There is a Reflectoradd-in for PowerShellthat will allow you to see the corresponding PowerShell script for static methods on classes
有一个用于 PowerShell的Reflector插件,可让您查看类上静态方法的相应 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/。
回答by White hawk
Adam Discroll has createda 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.
Adam Discroll创建了一个基于 Roslyn 的转换器,他甚至提供了一个在线代码转换器——它似乎适用于简单的脚本,但在 ie 静态成员或类方面存在问题。