`Add-Type` C# 6+ features throwing errors

耗尽温柔 提交于 2019-12-10 10:17:44

问题


I am trying to compile c# source code in powershell by using this command:

Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source

But c#-6.0 features are not working, for example:

Add-Type : c:\Users\...\AppData\Local\Temp\2\d2q5hn5b.0.cs(101) : Unexpected character '$'

For code:

new Problem($"... ({identifier})", node)

I am using powershell-v5.1

Is there a way to fix this?


回答1:


Powershell uses CodeDomProvider to compile their assemblies. The version provided with the framework just supports C# 5, so no new features are available by default.

However, if you provide another CodeDomProvider, you can compile any language, also C#6. There is a CodeDomProvider available for Roslyn (the new .NET compiler). You can download it from NuGet and include the assembly using Add-Type. Then create an instance of the compiler and pass that in the -CodeDomProvider attribute.




回答2:


To expand upon Patrick Hoffmans's solution, I was a bit uncomfortable about using the reflection method in unbob's solution as that could potentially break in the future.

I worked out the following powershell code instead which uses .NET named classes and interfaces:

#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.2.0.1'
Add-Type -Path "$DotNetCodeDomLocation\lib\net45\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()
    {
        return "$DotNetCodeDomLocation\tools\RoslynLatest\csc.exe"
    }
    [int] get_CompilerServerTimeToLive()
    {
        return 10
    }
}
"@
$DotNetCodeDomProvider = [Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider]::new([RoslynCompilerSettings]::new())

This can then be used as in the following examples:

  • To directly add a type to the powershell instance, with assembly reference example (requires the roslyn compiler and the above code to be bundled with your script):

    Add-Type -CodeDomProvider $DotNetCodeDomProvider -TypeDefinition $your_source_code_block -ReferencedAssemblies @([System.Reflection.Assembly]::GetAssembly([hashtable]).Location)
    
  • To compile the code to a dll for loading in future/other scripts (only requires the resulting dll file to be bundled with your script):

    $DotNetAssemblyParameters = [System.CodeDom.Compiler.CompilerParameters]::new(
        @([System.Reflection.Assembly]::GetAssembly([hashtable]).Location),
        'path_and_name_for_saved.dll',
        $false
    )
    # you can adjust more compilation settings here if you want, see
    # https://docs.microsoft.com/en-us/dotnet/api/system.codedom.compiler.compilerparameters?view=netframework-4.7.2
    $compilationResults = $DotNetCodeDomProvider.CompileAssemblyFromSource(
        $DotNetAssemblyParameters,
        $your_source_code_block
    )
    

The compiled dll can then be used with a simple Add-Type:

Add-Type -Path 'path_and_name_for_saved.Dll'

This allows for you to use the latest .NET compiler in powershell either inline with your main script if you bundle the CodeDomProvider dll and the roslyn compiler, or you can compile the C# code out to a dll so it doesn't have to be recompiled each time the script is run, allowing for easier portability and a faster script run time.




回答3:


When I try Mr. Hoffman's approach, I get the following error:

Add-Type : Could not find a part of the path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\bin\roslyn\csc.exe'.

user1676558 mentions two solutions:

  1. A NuGet package that contains a fix for this specific problem
  2. A snippet of C# that reflects out the offending private field and fixes it

Being a (little league) PowerShell hacker, I came up with my own PowerShellian solution, based on examination of the source code:

$dncpTypes = Add-Type -Path C:\<path where I put the dll>\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll -PassThru
$dncpTypTab = [ordered]@{}
$dncpTypes | %{$dncpTypTab[$_.Name] = $_}

$compSetCtor    = $dncpTypTab.CompilerSettings.GetConstructor(@([string],[int]))
$compSettings   = $compSetCtor.Invoke(@('C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe', 10))
$cscpOtherCtor  = $dncpTypTab.CSharpCodeProvider.GetConstructor('NonPublic,Instance', $null, @($dncpTypTab.ICompilerSettings), $null)
$roslynProvider = $cscpOtherCtor.Invoke($compSettings)

Needless to say, there's some discussion on the innertubes about whether or not this is a bug. Looks like the provider was targeted at ASP.NET and does the right thing there. People also disagree on where to pick up csc.exe. I suspect this may continue to be in flux.

[later edit: in VS2017, csc appears to live at ${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Roslyn\csc.exe.]



来源:https://stackoverflow.com/questions/40787766/add-type-c-sharp-6-features-throwing-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!