Zer*_*tul 3 c# powershell roslyn
我试图使用next命令在powershell中编译C#源代码:
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source
Run Code Online (Sandbox Code Playgroud)
但是C#6.0功能不起作用,例如:
new Problem($"... ({identifier})", node)
Run Code Online (Sandbox Code Playgroud)
代码:
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source
Run Code Online (Sandbox Code Playgroud)
我正在使用最新的PowerShell Add-Type : c:\Users\...\AppData\Local\Temp\2\d2q5hn5b.0.cs(101) : Unexpected character '$'
有没有办法来解决这个问题?
Powershell用于CodeDomProvider编译它们的程序集.随框架提供的版本仅支持C#5,因此默认情况下没有新功能可用.
但是,如果您提供另一种CodeDomProvider语言,则可以编译任何语言,也可以编译C#6.有一个CodeDomProvider可用于Roslyn(新的.NET编译器).您可以从NuGet下载它并使用包含组件Add-Type.然后创建编译器的实例并在-CodeDomProvider属性中传递它.
小智 7
为了扩展Patrick Hoffmans 的解决方案,我对在unbob 的解决方案中使用反射方法感到有点不舒服,因为这在未来可能会崩溃。
我编写了以下powershell代码,它使用.NET命名类和接口:
#requires -Version 5
# download https://www.nuget.org/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/
# and extract with 7-zip to a location, enter that location on the next line
$DotNetCodeDomLocation = 'C:\Utils\microsoft.codedom.providers.dotnetcompilerplatform'
Add-Type -Path "$DotNetCodeDomLocation\lib\net475\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"
# using Invoke-Expression moves this class definition to runtime, so it will work after the Add-Type
# and the ps5 class interface implementation will succeed. This uses the public interface ICompilerSettings
# instead of the private class CompilerSettings
Invoke-Expression -Command @"
class RoslynCompilerSettings : Microsoft.CodeDom.Providers.DotNetCompilerPlatform.ICompilerSettings
{
[string] get_CompilerFullPath()
{
// This path may need to be updated for newer versions
return "$DotNetCodeDomLocation\tools\Roslyn-4.1.0\csc.exe"
}
[int] get_CompilerServerTimeToLive()
{
return 10
}
}
"@
$DotNetCodeDomProvider = [Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider]::new([RoslynCompilerSettings]::new())
Run Code Online (Sandbox Code Playgroud)
然后可以像以下示例一样使用它:
要直接向实例添加类型powershell,请使用程序集参考示例(需要将roslyn编译器和上述代码与脚本捆绑在一起):
$addTypeSplat = @{
TypeDefinition = $your_source_code_block
ReferencedAssemblies = @([System.Reflection.Assembly]::GetAssembly([hashtable]).Location)
CodeDomProvider = $DotNetCodeDomProvider
}
Add-Type @addTypeSplat
Run Code Online (Sandbox Code Playgroud)
要将代码编译为dll供将来/其他脚本加载(仅需要将生成的dll文件与您的脚本捆绑在一起):
$addTypeSplat = @{
TypeDefinition = $your_source_code_block
ReferencedAssemblies = @([System.Reflection.Assembly]::GetAssembly([hashtable]).Location)
CodeDomProvider = $DotNetCodeDomProvider
}
Add-Type @addTypeSplat
Run Code Online (Sandbox Code Playgroud)
然后可以将编译后的代码dll与简单的命令一起使用Add-Type:
Add-Type -Path 'path_and_name_for_saved.Dll'
Run Code Online (Sandbox Code Playgroud)
.NET如果您捆绑了编译器,这允许您在主脚本中内联使用最新的编译器,powershell或者您可以将代码编译为 a ,这样就不必在每次运行脚本时重新编译,从而允许为了更容易移植和更快的脚本运行时间。CodeDomProvider dllroslynC#dll
| 归档时间: |
|
| 查看次数: |
2173 次 |
| 最近记录: |