如何在-path和-language csharpversion3中使用add-type?

sco*_*obi 3 powershell powershell-2.0

我一直在Powershell中使用add-type在我想使用的某些C#类中动态编译。效果很好,只限于2.0。

我刚刚发现了该-language csharpversion3选项,但不适用于-path。我该如何解决?

[编辑:删除了有关ReadAllText的内容-我弄错了。]

sco*_*obi 5

解决方法如下:以文本形式读取文件。

$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3
Run Code Online (Sandbox Code Playgroud)

我不妨粘贴其余内容,并以某种方式使此答案有用。.我有一个调试标志,可让我生成DLL,以便可以更轻松地插入调试器,并使用Reflector检查它,等等。

$cp = new-object codedom.compiler.compilerparameters
$cp.ReferencedAssemblies.Add('system.dll') > $null
$cp.ReferencedAssemblies.Add('system.core.dll') > $null

# optionally turn on debugging support
if ($debugscript)
{
    # delete old unused crap while we're at it
    dir "$($env:temp)\-*.dll" |%{
        del $_ -ea silentlycontinue
        if ($?) { del $_.fullname.replace('.dll', '.pdb') -ea silentlycontinue }
    }

    $cp.TreatWarningsAsErrors = $true
    $cp.IncludeDebugInformation = $true
    $cp.OutputAssembly = $env:temp + '\-' + [diagnostics.process]::getcurrentprocess().id + '.dll'
}

$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3 -compilerparam $cp
Run Code Online (Sandbox Code Playgroud)

如果$ debugscript设置为true,这将添加一些其他功能:

  • 将警告编译为错误
  • 生成一个PDB
  • 使用绑定到进程ID的特定DLL / PDB名称(在temp文件夹中),以便每个会话都有自己的名称。这有利于迭代对.cs的更改。
  • 删除旧的dll和pdb,在迭代时也很好。